Increment key if key already in dict
Solution 1:
A cleaner way is to use a mapping between key and a list of values for it. Use defaultdict for this. If a key isn't present, it will call the defaultfactory function* and returns it.
- here a default factory function is the
list
function that returns an empty list
from collections import defaultdict
# foo=[("a", "bar"), ("a", "bazz")] # some random input that maps keys to values, and keys repeat
d = defaultdict(list) # return empty list if key doesn't exist
for k, val in foo:
d[k].append(val)
# If you don't want a simple dict instead of defaultdict
d = dict(d)
print(d)
>>>{'a': ['bar', 'bazzz']}
You can also do this without defaultdict with dict's setdefault method.
# foo=[("a", "bar"), ("a", "bazz")]
d = {}
for k, val in foo:
# set [] as the default value for k if k doesn't already exist, and return the value of k
d.setdefault(k,[]).append(val)
print(d)
>>>{'a': ['bar', 'bazzz']}