如何从字符串列表中创建字典?

时间:2015-08-01 22:55:59

标签: list python-3.x dictionary

所以,我有这个,例如:

['Apple', 'Red', 'Banana', 'Yellow']

我需要返回

 {'Apple': 'Red', 'Banana': 'Yellow'}

有办法做到这一点吗?

3 个答案:

答案 0 :(得分:1)

只需将列表切片并使用dict

>>> li=['Apple', 'Red', 'Banana', 'Yellow']
>>> dict((li[:2],li[2:]))
{'Apple': 'Red', 'Banana': 'Yellow'}

答案 1 :(得分:1)

如果它是[k1, v1, k2, v2, ...]之类的列表,只需使用切片和zip

>>> l = ['Apple', 'Red', 'Banana', 'Yellow']
>>> dict(zip(l[::2], l[1::2]))
{'Banana': 'Yellow', 'Apple': 'Red'}

像这样你首先创建两个列表,一个包含键,另一个包含值:

>>> k, v = l[::2], l[1::2]
>>> k
['Apple', 'Banana']
>>> v
['Red', 'Yellow']

然后zip创建元组的迭代器(在这种情况下为键和值对):

>>> list(zip(k, v))
[('Apple', 'Red'), ('Banana', 'Yellow')]

然后可以使用此迭代器创建字典。

答案 2 :(得分:0)

对于Python 3.x,您可以使用dict comprehension syntax

d = {key: value for (key, value) in item}

您可以以任何方式使用该项目。

相关问题