Python:将列表转换为带有索引的字典
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36459969/
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
Python: Convert list to dictionary with indexes
提问by ahajib
I am trying to convert the following list:
我正在尝试转换以下列表:
list = ['A','B','C']
To a dictionary like:
像这样的字典:
dict = {'A':0, 'B':1, 'C':2}
I have tried answers from other posts none which is working for me. I have the following code for now:
我已经尝试过其他帖子的答案,没有一个对我有用。我现在有以下代码:
{list[i]: i for i in range(len(list))}
Which gives me this error:
这给了我这个错误:
unhashable type: 'list'
Any help is much appreciated. Thanks.
任何帮助深表感谢。谢谢。
回答by Abhijit
You can get the indices of a list from the built-in enumerate. You just need to reverse the index value map and use a dictionary comprehension to create a dictionary
您可以从内置的enumerate获取列表的索引。您只需要反转索引值映射并使用字典理解来创建字典
>>> lst = ['A','B','C']
>>> {k: v for v, k in enumerate(lst)}
{'A': 0, 'C': 2, 'B': 1}
Ohh, and never name a variable to a built-in or a type.
哦,永远不要将变量命名为内置变量或类型。
回答by florex
Use built-in functions dict and zip :
使用内置函数 dict 和 zip :
>>> lst = ['A','B','C']
>>> dict(zip(lst,range(len(lst))))
回答by Sohaib Farooqi
Python dict
constructor has an ability to convert list of tuple
to dict
, with key as first element of tuple and value as second element of tuple. To achieve this you can use builtin function enumerate
which yield tuple
of (index, value)
.
Pythondict
构造函数能够将列表转换tuple
为dict
,键作为元组的第一个元素,值作为元组的第二个元素。要做到这一点,你可以使用内置函数 enumerate
,其产生tuple
的(index, value)
。
However question's requirement is exact opposite i.e. tuple
should be (value, index)
. So this requires and additional step to reverse the tuple elements before passing to dict constructor. For this step we can use builtin reversed
and apply it to each element of list using map
然而问题的要求恰恰相反,即tuple
应该是(value, index)
。因此,在传递给 dict 构造函数之前,这需要额外的步骤来反转元组元素。对于这一步,我们可以使用 builtinreversed
并将其应用于列表的每个元素map
>>> lst = ['A', 'B', 'C']
>>> dict(map(reversed, enumerate(lst)))
>>> {'A': 0, 'C': 2, 'B': 1}
回答by gr1zzly be4r
Don't use list
as your variable name because it's reserved by Python. You can also take advantage of enumerate
.
不要list
用作变量名,因为它是 Python 保留的。您还可以利用enumerate
.
your_list = ['A', 'B', 'C']
dict = {key: i for i, key in enumerate(your_list)}
回答by Daniel
You have to convert the unhashable list into a tuple:
您必须将不可散列的列表转换为元组:
dct = {tuple(key): idx for idx, key in enumerate(lst)}