简体   繁体   English

将2个元素列表转换为dict

[英]Convert 2 element list into dict

I know about few of the questions answered here on SO about dict(list) ie 我知道这里回答的关于dict(list)的问题很少,即

l = [['a',1] ['b',2]]

and do dict(l) then we get: 并做dict(l)然后我们得到:

{'a': 1, 'b': 2}

But how to make a list with 2 elements 但是如何制作一个包含2个元素的列表

l = ['a',1]

become a dictionary such as: 成为一本字典,如:

{'a':1}

using the dict function? 使用dict函数?

dict expects an iterable of two-item iterables, so you will need to put l in a list: dict期望一个可迭代的两项迭代,所以你需要把l放在一个列表中:

>>> l = ['a',1]
>>> dict([l])
{'a': 1}
>>>

Note that you could also use a tuple: 请注意,您还可以使用元组:

>>> l = ['a',1]
>>> dict((l,))
{'a': 1}
>>>

This works for multiple elements in the list 这适用于列表中的多个元素

>>> l = ['a',1,'b',2]
>>> i = [(l[i],l[i+1]) for i in range(0,len(l),2)]
>>> dict(i)
{'a': 1, 'b': 2}

For one element, dict([l]) would work. 对于一个元素, dict([l])将起作用。 For multiple key/value pairs in a flattened list, you could use zip() : 对于展平列表中的多个键/值对,您可以使用zip()

In [5]: l = ['a', 1, 'b', 2]

In [6]: dict(zip(l[::2], l[1::2]))
Out[6]: {'a': 1, 'b': 2}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM