I have an association list with repeated keys:
l = [(1, 2), (2, 3), (1, 3), (2, 4)]
and I want a dict with list values:
d = {1: [2, 3], 2: [3, 4]}
Can I do better than:
for (x,y) in l:
try:
z = d[x]
except KeyError:
z = d[x] = list()
z.append(y)
You can use the dict.setdefault() method to provide a default empty list for missing keys:
for x, y in l:
d.setdefault(x, []).append(y)
or you could use a defaultdict() object to create empty lists for missing keys:
from collections import defaultdict
d = defaultdict(list)
for x, y in l:
d[x].append(y)
but to switch off the auto-vivication behaviour you'd have to set the default_factory attribute to None:
d.default_factory = None # switch off creating new lists
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With