如何使用列表中的键创建字典,默认值为(否)为零? [英] How do I create a dictionary with keys from a list and values defaulting to (say) zero?
本文介绍了如何使用列表中的键创建字典,默认值为(否)为零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有 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?
推荐答案
dict((el,0)for a a) code>将正常运行。
dict((el,0) for el in a)
will work well.
Python 2.7及以上版本也支持字典推理。那个语法是 {el:0 for el in a}
。
Python 2.7 and above also support dict comprehensions. That syntax is {el:0 for el in a}
.
这篇关于如何使用列表中的键创建字典,默认值为(否)为零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文