[英]Convert a list of tuples to dictionary
I have a list of tuples that I would like to convert to a dictionary.我有一个要转换为字典的元组列表。 Each of the tuples in the list has four elements:
列表中的每个元组都有四个元素:
N = [('WA', 'OR', 'CA', 'HI'), ('MA', 'NY', 'PA', 'FL')]
How do I get a dictionary set up where the first element of the tuple is the key, and the value is a tuple of the rest of the elements?如何设置字典,其中元组的第一个元素是键,值是元素的 rest 的元组?
dict = {"WA": ("OR", "CA", "HI"), "MA": ("NY", "PA", "FL")}
I tried something along the lines of this, but I am getting a truncated version of the fourth element (at least that what it looks like to me, my actual list is much larger than the example list):我尝试了一些类似的东西,但是我得到了第四个元素的截断版本(至少在我看来,我的实际列表比示例列表大得多):
for i in range(len(N))}:
for v in N[i]:
dict[i] = v[1:4]
Think about it inside out.从里到外想一想。 Given a single tuple, how do you make a key value pair?
给定一个元组,如何创建键值对?
tup[0]: tup[1:]
Now just wrap this in the dictionary:现在只需将其包装在字典中:
d = {tup[0]: tup[1:] for tup in N}
Try this尝试这个
>>> N = [('WA', 'OR', 'CA', 'HI'), ('MA', 'NY', 'PA', 'FL')]
>> d = {key: (*values,) for key, *values in N}
>>> d
{'WA': ('OR', 'CA', 'HI'), 'MA': ('NY', 'PA', 'FL')}
for key, *values in N
means that it will take the first element of each tuple as key
, and it will put the remaining elements in values
. for key, *values in N
表示它将每个元组的第一个元素作为key
,并将其余元素放在values
中。
In your code v[1:4]
is already each element of the tuple.在您的代码中,
v[1:4]
已经是元组的每个元素。 That is why the first character is ignored.这就是忽略第一个字符的原因。
You don't need a nested loop.您不需要嵌套循环。
You can use a dict comprehension (obviously use better variable names):您可以使用 dict 理解(显然使用更好的变量名):
N = [('WA', 'OR', 'CA', 'HI'), ('MA', 'NY', 'PA', 'FL')]
d = {t[0]: t[1:] for t in N}
print(d)
outputs输出
{'WA': ('OR', 'CA', 'HI'), 'MA': ('NY', 'PA', 'FL')}
You could also use dict
directly.您也可以直接使用
dict
。 It accepts an iterable of tuples where the first element will be the key and the second element will be the value.它接受一个可迭代的元组,其中第一个元素是键,第二个元素是值。
d = dict((t[0], t[1:]) for t in N)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.