如何将键值元组列表转换成字典? [英] How to convert list of key-value tuples into dictionary?

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

问题描述

我有一个看起来像这样的列表:

I have a list that looks like:

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

我想把它变成一个像这样的字典

I 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?

我的元组列表实际上更像是:

My list of tuples is actually more like:

[(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).

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

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