如何使用列表中的键和分隔空列表的值创建字典?

How do I create a dictionary with keys from a list and values separate empty lists?

How do I create a dictionary with keys from a list and values defaulting to (say) zero? 构建 尤其是 this answer:

如何使用列表中的键和分隔空列表的值创建字典?
(稍后,我将能够附加元素)

使用字典理解,

{item: [] for item in my_list}

您只是迭代列表并为每个键创建一个新列表。

或者,您可以考虑使用 collections.defaultdict,像这样

from collections import defaultdict
d = defaultdict(list)
for item in my_list:
    d[item].append(whatever_value)

在这里,我们传递给 defaultdict 的函数对象是主要的。如果字典中不存在该键,它将被调用以获取值。

这个实现简单易行,不言自明,我们遍历列表中的所有元素并在字典中为每个值创建一个唯一的条目并用一个空列表对其进行初始化

sample_list = [2,5,4,6,7]
sample_dict = {}
for i in sample_list:
    sample_dict[i] = []

通过正常方法:

>>> l = ["a", "b", "c"]
>>> d = {}
>>> for i in l:
...   d[i] = []
... 
>>> d
{'a': [], 'c': [], 'b': []}
>>> 

通过使用collections模块

>>> l = ["a", "b", "c"]
>>> import collections
>>> d = collections.defaultdict(list)
>>> for i in l:
...   d[i]
... 
[]
[]
[]
>>> d
defaultdict(<type 'list'>, {'a': [], 'c': [], 'b': []})