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

标签 python list dictionary

建筑自 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 的函数对象是主要的。如果字典中不存在该键,它将被调用以获取值。

关于python - 如何使用列表中的键和分隔空列表的值创建字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28194184/

相关文章:

python - 如何将最后一次出现的列表作为输出?

Python dict 是本地的,而不是引用

python - coffeescript 字典设置为默认值

python - 从字符串创建列表字典

python - 限制每组 n 个结果 - Django queryset

python - pyserial 没有输出

python - 在 Vim 中使用 Python 2 和 3(在 Windows 上)

python - 使用 Python 将索引设置为 csv 文件中重复行值的组

python - 为什么 python 列表会这样做?

list - Clojure:跨列表的复杂迭代?