Inverting a dictionary of lists in Python | Hugonweb Annotated Link Bibliography
https://stackoverflow.com/questions/35491223/inverting-a-dictionary-with-list-values
I've needed to do this countless times in particle physics data analysis and other areas.
What I've done before:
data = {'a' : ['alpha', "beta"], 'b' : ["alpha"]}
result = {}
for key in data:
for value in data[key]:
try:
result[value].append(key)
except KeyError:
result[value] = [key]
and the simpler solutions suggested in the link:
data = {'a' : ['alpha', "beta"], 'b' : ["alpha"]}
result = {}
for key in data:
for value in data[key]:
result.setdefault(value,[]).append(key)
or
from collections import defaultdict
data = {'a' : ['alpha', "beta"], 'b' : ["alpha"]}
result = defaultdict(list)
for key in data:
for value in data[key]:
result[value].append(key)
dict.setdefault
and collections.defaultdict
are new to me and useful!