Python 如何使用列表中的键和默认为(例如)零的值创建字典?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3869487/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:07:09  来源:igfitidea点击:

How do I create a dictionary with keys from a list and values defaulting to (say) zero?

pythondictionary

提问by blahster

I have a = [1,2,3,4]and I want d = {1:0, 2:0, 3:0, 4:0}

我有a = [1,2,3,4]而且我想要d = {1:0, 2:0, 3:0, 4:0}

d = dict(zip(q,[0 for x in range(0,len(q))]))

works but is ugly. What's a cleaner way?

有效,但很丑。什么是更清洁的方法?

采纳答案by Tim McNamara

dict((el,0) for el in a)will work well.

dict((el,0) for el in a)会很好用。

Python 2.7 and above also support dict comprehensions. That syntax is {el:0 for el in a}.

Python 2.7 及更高版本也支持字典推导式。该语法是{el:0 for el in a}.

回答by GWW

d = dict([(x,0) for x in a])

**edit Tim's solution is better because it uses generators see the comment to his answer.

**编辑蒂姆的解决方案更好,因为它使用了生成器,请参阅对他的回答的评论。

回答by intuited

In addition to Tim's answer, which is very appropriate to your specific example, it's worth mentioning collections.defaultdict, which lets you do stuff like this:

除了 Tim 的回答(非常适合您的具体示例)之外,值得一提的是collections.defaultdict,它可以让您执行以下操作:

>>> d = defaultdict(int)
>>> d[0] += 1
>>> d
{0: 1}
>>> d[4] += 1
>>> d
{0: 1, 4: 1}

For mapping [1, 2, 3, 4]as in your example, it's a fish out of water. But depending on the reason you asked the question, this may end up being a more appropriate technique.

对于[1, 2, 3, 4]您的示例中的映射,它是一条离开水的鱼。但根据您提出问题的原因,这可能最终成为一种更合适的技术。

回答by eumiro

d = dict.fromkeys(a, 0)

ais the list, 0is the default value. Pay attention not to set the default value to some mutable object (i.e. list or dict), because it will be one object used as value for every key in the dictionary (check herefor a solution for this case). Numbers/strings are safe.

a是列表,0是默认值。注意不要将默认值设置为某些可变对象(即列表或字典),因为它将是一个对象,用作字典中每个键的值(请在此处查看针对这种情况的解决方案)。数字/字符串是安全的。

回答by Andrey

In python version >= 2.7 and in python 3:

在 python 版本 >= 2.7 和 python 3 中:

d = {el:0 for el in a}