[英]Python - how to convert a list with tuples into a dictonary with two values
iam searching for a small and easy possibility to convert a list with tuples into a dictonary which has one key and two values.我正在寻找一种小而简单的可能性,将带有元组的列表转换为具有一个键和两个值的字典。 When possible with no external libary.尽可能不使用外部库。
l1 = ["a","b","c"]
l2 = [1, 2, 3]
l3 = [11,22,33]
mylist = list(zip(l1, l2, l3))
**output:**
[('a', 1, 11), ('b', 2, 22), ('c', 3, 33)]
**i tried:**
mydict = {}
mydict = dict(mylist)
**Error:**
Traceback (most recent call last):
File "", line 8, in <module>
dictonary = dict(mylist)
ValueError: dictionary update sequence element #0 has length 3; 2 is required
**the solution should look like:**
{'a': (1, 11),'b': (2, 22),'c': (3, 33)} or
{'a': [1, 11],'b': [2, 22],'c': [3, 33]}
Thanks in advance提前致谢
Simple enough, nesting the zip
to make sure you call the dict
constructor with an iterable over pairs :很简单,嵌套zip
以确保您使用可迭代的对调用dict
构造函数:
l1 = ["a","b","c"]
l2 = [1, 2, 3]
l3 = [11,22,33]
dct = dict(zip(l1, zip(l2, l3)))
# {'a': (1, 11), 'b': (2, 22), 'c': (3, 33)}
Or, using a dict
comprehension and starting from your intermediate list of triplets (but works for iterables of any length > 0):或者,使用dict
理解并从三元组的中间列表开始(但适用于任何长度 > 0 的迭代):
dct = {h: t for h, *t in mylist}
# {'a': [1, 11], 'b': [2, 22], 'c': [3, 33]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.