简体   繁体   English

在Python中为列表的dict添加值?

[英]Add values to dict of list in 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. 我找了重复,没找到,但也许我只是不知道使用正确的关键字。

What you want is called a defaultdict, as available in the collections library: 你想要的是一个defaultdict,在集合库中可用:

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])]

d[key] = d.get(key, []) + [value]

to explain 解释
d.get method returns value under the key key and if there is no such key, returns optional argument (second), in this case [] (empty list) d.get方法的关键下返回值key ,并且如果存在这样的密钥,则返回可选的参数(第二),在这种情况下[]空列表)

then you will get the list (empty or not) and than you add list [value] to it. 那么你将获得列表(空或不),而不是你添加列表[value] this can be also done by .append(value) instead of + [value] 这也可以通过.append(value)而不是+ [value]

having that list, you set it as the new value to that key 拥有该列表,您将其设置为该键的新值

eg 例如

d = {1: [1, 2]}
d[1] = d.get(1, []) + [3]
# d == {1: [1, 2, 3]}

d[17] = d.get(17, []) + [8]
# d == {1: [1, 2, 3], 17: [8]}
d[key] = list() if (key not in d) else d[key].append(value) 

Uses the ternary operators. 使用三元运算符。 And looks somewhat cleaner, however it is still almost identical to your scenario. 并且看起来有点干净,但它仍然几乎与您的场景完全相同。

I apologize, I wasn't thinking earlier and used standard ternary operators. 我道歉,我之前没想过并且使用过标准的三元运算符。 I changed them to Python ternary operators. 我将它们改为Python三元运算符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM