Reputation: 60004
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)
Upvotes: 5
Views: 1344
Reputation: 251363
You can use collections.defaultdict
:
d = collections.defaultdict(list)
for k, v in l:
d[k].append(v)
Upvotes: 5
Reputation: 1121584
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
Upvotes: 9