Add values to dict of list in Python?
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] = 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.
d[key] = d.get(key, []) + [value]
to explaind.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]}