简体   繁体   中英

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)

You can use thedict.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

You can use collections.defaultdict :

d = collections.defaultdict(list)
for k, v in l:
    d[k].append(v)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM