在 Python 中将列表转换为字典
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4576115/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert a list to a dictionary in Python
提问by Mike
Let's say I have a list ain Python whose entries conveniently map to a dictionary. Each even element represents the key to the dictionary, and the following odd element is the value
假设我有一个aPython列表,其条目可以方便地映射到字典。每个偶数元素代表字典的键,后面的奇数元素是值
for example,
例如,
a = ['hello','world','1','2']
and I'd like to convert it to a dictionary b, where
我想将其转换为字典b,其中
b['hello'] = 'world'
b['1'] = '2'
What is the syntactically cleanest way to accomplish this?
实现此目的的语法最干净的方法是什么?
采纳答案by kindall
b = dict(zip(a[::2], a[1::2]))
If ais large, you will probably want to do something like the following, which doesn't make any temporary lists like the above.
如果a很大,您可能想要执行以下操作,它不会像上面那样创建任何临时列表。
from itertools import izip
i = iter(a)
b = dict(izip(i, i))
In Python 3 you could also use a dict comprehension, but ironically I think the simplest way to do it will be with range()and len(), which would normally be a code smell.
在 Python 3 中,您也可以使用 dict 推导式,但具有讽刺意味的是,我认为最简单的方法是使用range()and len(),这通常是代码异味。
b = {a[i]: a[i+1] for i in range(0, len(a), 2)}
So the iter()/izip()method is still probably the most Pythonic in Python 3, although as EOL notes in a comment, zip()is already lazy in Python 3 so you don't need izip().
因此,该iter()/izip()方法可能仍然是 Python 3 中最 Pythonic的方法,尽管正如 EOL 在评论中指出的那样,zip()在 Python 3 中已经是惰性的,因此您不需要izip().
i = iter(a)
b = dict(zip(i, i))
If you want it on one line, you'll have to cheat and use a semicolon. ;-)
如果你想在一行上,你必须作弊并使用分号。;-)
回答by sahhhm
May not be the most pythonic, but
可能不是最pythonic的,但是
>>> b = {}
>>> for i in range(0, len(a), 2):
b[a[i]] = a[i+1]
回答by JobJob
Simple answer
简单的回答
Another option (courtesy of Alex Martelli https://stackoverflow.com/a/2597178/104264):
另一种选择(亚历克斯 Martelli https://stackoverflow.com/a/2597178/104264 提供):
dict(x[i:i+2] for i in range(0, len(x), 2))
Related note
相关说明
If you have this:
如果你有这个:
a = ['bi','double','duo','two']
and you want this (each element of the list keying a given value (2 in this case)):
并且你想要这个(列表的每个元素都键入一个给定的值(在这种情况下为 2)):
{'bi':2,'double':2,'duo':2,'two':2}
you can use:
您可以使用:
>>> dict((k,2) for k in a)
{'double': 2, 'bi': 2, 'two': 2, 'duo': 2}
回答by Manu
I am not sure if this is pythonic, but seems to work
我不确定这是否是 pythonic,但似乎有效
def alternate_list(a):
return a[::2], a[1::2]
key_list,value_list = alternate_list(a)
b = dict(zip(key_list,value_list))
回答by Chris Arena
You can use a dict comprehension for this pretty easily:
你可以很容易地使用字典理解:
a = ['hello','world','1','2']
my_dict = {item : a[index+1] for index, item in enumerate(a) if index % 2 == 0}
This is equivalent to the for loop below:
这相当于下面的 for 循环:
my_dict = {}
for index, item in enumerate(a):
if index % 2 == 0:
my_dict[item] = a[index+1]
回答by Stefan Gruenwald
You can also do it like this (string to list conversion here, then conversion to a dictionary)
你也可以这样做(字符串在这里列出转换,然后转换为字典)
string_list = """
Hello World
Goodbye Night
Great Day
Final Sunset
""".split()
string_list = dict(zip(string_list[::2],string_list[1::2]))
print string_list
回答by Oleksiy
I am also very much interested to have a one-liner for this conversion, as far such a list is the default initializer for hashed in Perl.
我也非常有兴趣为这种转换创建一个单行,因为这样的列表是 Perl 中散列的默认初始值设定项。
Exceptionally comprehensive answer is given in this thread -
此线程中给出了非常全面的答案-
Mine one I am newbie in Python), using Python 2.7 Generator Expressions, would be:
我的一个我是 Python 新手),使用Python 2.7 Generator Expressions,将是:
dict((a[i], a[i + 1]) for i in range(0, len(a) - 1, 2))
dict((a[i], a[i + 1]) for i in range(0, len(a) - 1, 2))
回答by rix
Something i find pretty cool, which is that if your list is only 2 items long:
我觉得很酷的事情是,如果您的列表只有 2 个项目长:
ls = ['a', 'b']
dict([ls])
>>> {'a':'b'}
Remember, dict accepts any iterable containing an iterable where each item in the iterable must itself be an iterable with exactly two objects.
请记住, dict 接受任何包含可迭代对象的可迭代对象,其中可迭代对象中的每个项目本身必须是具有两个对象的可迭代对象。
回答by topkara
You can do it pretty fast without creating extra arrays, so this will work even for very large arrays:
您可以在不创建额外数组的情况下快速完成,因此即使对于非常大的数组也可以使用:
dict(izip(*([iter(a)]*2)))
If you have a generator a, even better:
如果你有一个 generator a,那就更好了:
dict(izip(*([a]*2)))
Here's the rundown:
这是纲要:
iter(h) #create an iterator from the array, no copies here
[]*2 #creates an array with two copies of the same iterator, the trick
izip(*()) #consumes the two iterators creating a tuple
dict() #puts the tuples into key,value of the dictionary
回答by muhammed
try below code:
试试下面的代码:
>>> d2 = dict([('one',1), ('two', 2), ('three', 3)])
>>> d2
{'three': 3, 'two': 2, 'one': 1}

