在Python中将值添加到列表的字典吗? [英] Add values to dict of list in Python?

查看:88
本文介绍了在Python中将值添加到列表的字典吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种列表的字典,最初是空的:

I have this kind of dictionary of lists, initially empty:

d = dict()

现在,用例是简单地在键下添加一个值到列表中,键可以是新键或现有键.我认为我们必须这样做:

Now the use case is to simply add a value to list under a key, which might be a new or an existing key. I think we have to do it like this:

if key not in d:
    d[key] = list()
d[key].append(value)

这似乎很繁琐且容易出错,需要写多行(使用复制粘贴或辅助功能).有更方便的方法吗?

This seems awfully tedious and error-prone, needing to write multiple lines (with copy-paste or helper function). Is there a more convenient way?

如果没有只有一种方法可以做到",而您知道,您也可以回答,甚至可以建议其他方法来完成上述任务,即使不是一定更好.

If there isn't "only one way to do it", and you know it, you can also answer that, and maybe suggest alternative ways to accomplish above, even if they aren't necessarily better.

我寻找重复项,但没有找到,但也许我只是不知道使用正确的关键字.

I looked for duplicate, didn't find, but perhaps I just didn't know to use right keywords.

推荐答案

您想要的称为defaultdict,如收藏库中所述:

What you want is called a defaultdict, as available in the collections library:

Python2.7: https://docs.python.org/2/library/collections.html#defaultdict-examples

Python2.7: https://docs.python.org/2/library/collections.html#defaultdict-examples

Python3.7: https://docs.python.org/3/library/collections.html#collections.defaultdict

Python3.7: https://docs.python.org/3/library/collections.html#collections.defaultdict

Example:
>>> from collections import defaultdict
>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
...     d[k].append(v)
...
>>> sorted(d.items())
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

这篇关于在Python中将值添加到列表的字典吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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