Python:将键值元组的列表转换为字典? [英] Python: Convert list of key-value tuples into dictionary?

查看:514
本文介绍了Python:将键值元组的列表转换为字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的列表

[(A, 1), (B, 2), (C, 3)]

想要将其变成一个看起来像

And want to turn it into a dictionary that looks like

(A: 1, B: 2, C: 3)

最好的方法是什么?谢谢。

What's the best way to go about this? Thanks.

编辑:其实更像是

[(A, 12937012397), (BERA, 2034927830), (CE, 2349057340)]


推荐答案


这给我同样的错误,试图拆分列表和压缩它。 ValueError:字典更新序列元素#0的长度为1916; 2需要

This gives me the same error as trying to split the list up and zip it. ValueError: dictionary update sequence element #0 has length 1916; 2 is required

这是您的实际问题。

答案是您的列表中的元素不是您认为的元素。如果您键入 myList [0] ,您会发现列表的第一个元素不是二元组,例如('A',1),而是一个1916长度的迭代。

The answer is that the elements of your list are not what you think they are. If you type myList[0] you will find that the first element of your list is not a two-tuple, e.g. ('A', 1), but rather a 1916-length iterable.

一旦你实际上在您的原始问题( myList = [('A',1),('B',2)...] ),你需要做的只是 dict(myList)

Once you actually have a list in the form you stated in your original question (myList = [('A',1),('B',2),...]), all you need to do is dict(myList).

这篇关于Python:将键值元组的列表转换为字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆