[英]In Python: Create a dictionary from a list of keys, but set all values to 0?
I've found elegant solutions to create dictionaries from two lists:我找到了从两个列表创建字典的优雅解决方案:
keys = [a, b, c]
values = [1, 2, 3]
list_dict = {k:v for k,v in zip(keys, values)}
But I haven't been able to write something for a list of keys with a single value (0) for each key.但是我无法为每个键具有单个值 (0) 的键列表编写一些内容。 I've tried to do something like:
我试过做这样的事情:
list_dict = {k:v for k,v in (zip(keys,[0 for i in range(keys)]))}
But it should be possible with syntax something simple like:但是应该可以使用简单的语法,例如:
dict_totals = {k:v for k,v in zip(keys,range(0,3))}
I'm hoping for output that looks like {a:0, b:0, c:0}.我希望输出看起来像 {a:0, b:0, c:0}。 Am I missing something obvious?
我错过了一些明显的东西吗?
Using dict.fromkeys
alternate initialiser:使用
dict.fromkeys
备用初始化程序:
dict.fromkeys(keys, 0)
And offering you an easier way to do the first one:并为您提供一种更简单的方法来完成第一个:
dict(zip(keys, values))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.