简体   繁体   English

在 Python 中:从键列表创建字典,但将所有值设置为 0?

[英]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.

相关问题 如何用Python中的键列表和值字典创建字典? - How to create a dictionary from a list of keys and a dictionary of values in Python? 用4个键创建字典,从列表中分配值 - Create a dictionary with 4 keys assigning values from a list 从密钥列表中获取Python字典中的值 - Get values in Python dictionary from list of keys 使用键列表从Python字典中收集值 - Collecting values from a Python dictionary with list of keys Python 字典:为字典中的所有键创建一个列表,为字典中的所有值创建另一个列表 - Python Dictionary: Create a list for all keys in dict, another for all values in dict 根据嵌套字典列表中的匹配键创建值字典 - create dictionary of values based on matching keys in list from nested dictionary 如何将列表列表中的值分配给键以在 python 中创建字典 - How to assign values in list of list to keys to create dictionary in python Python - 如何从另一个列表创建一个字典列表,该列表具有两个具有多个值的键? - Python - How to create a dictionary list from another list which having two keys with multiple values? Python:map 字典键与列表中的值以使用 for 循环创建新列表 - Python: map dictionary keys with values from a list to create a new list using for loop 如何使用 Python 中的特定键从字典列表中创建字典 - How to create a dictionary from a list of dictionary using specific keys in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM