Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 842
hyde Avatar asked Sep 14 '18 16:09

hyde


2 Answers

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])]
like image 153
2080 Avatar answered Oct 10 '22 11:10

2080


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

e.g.

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]}
like image 36
Superior Avatar answered Oct 10 '22 11:10

Superior