Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a list of tuples with repeated keys to a dictionary of lists

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)
like image 737
sds Avatar asked Dec 09 '22 04:12

sds


1 Answers

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
like image 162
Martijn Pieters Avatar answered Dec 11 '22 11:12

Martijn Pieters