Python 一个班轮:从列表中创建一个以索引为键的字典
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/16607704/
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
One liner: creating a dictionary from list with indices as keys
提问by Nawaz
I want to create a dictionary out of a given list, in just one line. The keys of the dictionary will be indices, and values will be the elements of the list. Something like this:
我想从给定的列表中创建一个字典,只需一行。字典的键是索引,值是列表的元素。像这样的东西:
a = [51,27,13,56]         #given list
d = one-line-statement    #one line statement to create dictionary
print(d)
Output:
输出:
{0:51, 1:27, 2:13, 3:56}
I don't have any specific requirements as to why I want oneline. I'm just exploring python, and wondering if that is possible.
我对为什么要一条线没有任何具体要求。我只是在探索 python,想知道这是否可能。
采纳答案by glglgl
a = [51,27,13,56]
b = dict(enumerate(a))
print(b)
will produce
会产生
{0: 51, 1: 27, 2: 13, 3: 56}
Return an enumerate object. sequencemust be a sequence, an iterator, or some other object which supports iteration. The
next()method of the iterator returned byenumerate()returns atuplecontaining a count (from startwhich defaults to 0) and the values obtained from iterating over sequence:
返回一个枚举对象。序列必须是序列、迭代器或其他支持迭代的对象。
next()返回的迭代器的方法enumerate()返回一个tuple包含计数(从start默认为 0)和迭代序列获得的值:
回答by Stefano Sanfilippo
Try enumerate: it will return a list (or iterator) of tuples (i, a[i]), from which you can build a dict:
尝试enumerate:它将返回一个元组列表(或迭代器)(i, a[i]),您可以从中构建一个dict:
a = [51,27,13,56]  
b = dict(enumerate(a))
print b
回答by kiriloff
With another constructor, you have
使用另一个构造函数,你有
a = [51,27,13,56]         #given list
d={i:x for i,x in enumerate(a)}
print(d)
回答by Emilio M Bumachar
{x:a[x] for x in range(len(a))}
回答by Shahrukh khan
Simply use list comprehension.
只需使用列表理解即可。
a = [51,27,13,56]  
b = dict( [ (i,a[i]) for i in range(len(a)) ] )
print b

