如何使用列表中的键创建字典并分别列出空列表? [英] How do I create a dictionary with keys from a list and values separate empty lists?

查看:570
本文介绍了如何使用列表中的键创建字典并分别列出空列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用列表中的键创建字典,默认值为(否)为零)?
,特别是
此答案

如何使用列表中的键创建字典,并分别列出空列表? _
(之后,我可以附加元素)

How do I create a dictionary with keys from a list and values separate empty lists?
(Where, later on, I'll be able to append elements)

推荐答案

使用字典理解

{item: [] for item in my_list}

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

You are simply iterating the list and creating a new list for every key.

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

Alternatively, you can think about using collections.defaultdict, like this

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

这里,我们传递给 defaultdict 的函数对象是主要的东西。如果该字典中不存在该键,则会调用该值。

Here, the function object which we pass to defaultdict is the main thing. It will be called to get a value if the key doesn't exist in the dictionary.

这篇关于如何使用列表中的键创建字典并分别列出空列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆