在python中将列表转换为字典
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42720875/
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
Converting a list to dictionary in python
提问by codenamered5
I've gone through many questions but couldn't find what i was looking for.
I have a list something like this:
[2, 3, 5, 7, 11]
and I want to convert it into a dictionary in the format:
i.e. the values of the list should be keys and each associated value should be zero.
{2:0 , 3:0 , 5:0 , 7:0 , 11:0}
我已经解决了很多问题,但找不到我要找的东西。我有一个类似这样的列表:
[2, 3, 5, 7, 11]
我想将它转换为以下格式的字典:即列表的值应该是键,每个关联的值应该为零。
{2:0 , 3:0 , 5:0 , 7:0 , 11:0}
回答by Ma0
A dict comprehension will do.
一个字典理解就可以了。
my_list = [2, 3, 5, 7, 11]
my_dict = {k: 0 for k in my_list} # {2:0 , 3:0 , 5:0 , 7:0 , 11:0}
Even if you are not familiar at all with comprehensions you could still do an explicit for
-loop:
即使您根本不熟悉for
推导式,您仍然可以执行显式的-loop:
my_dict = {}
for k in my_list:
my_dict[k] = 0
回答by Ambitions
Another solution:
另一种解决方案:
l = [2, 3, 5, 7, 11]
d = {}
for item in l:
d[item] = 0