简体   繁体   中英

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:

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

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)

then you will get the list (empty or not) and than you add list [value] to it. this can be also done by .append(value) instead of + [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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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