Return A Dictionary With Keys For A Given Dictionary's Values And Vice Versa
How would I, in a function, create a dictionary who's keys are a given dictionary's values, and vice versa, where the given dictionary has multiple values per key? For example, giv
Solution 1:
Try:
{letter: [key for key in d if letter in d[key]] for letter in set(letter for key in d for letter in d[key])}
Explanation: set(letter for key in d for letter in d[key])
is a set of all letters that appears in the original dict. Then we make a new dict, in which every entry is letter: [key for key in d if letter in d[key]]
, which means one of the letters, mapping to a list of numbers that mapped to it in the original dict.
Solution 2:
Easy using collections.defaultdict()
which defaults as list
- loop on the sorted key/value couple
- inner loop on the value items
- for each value item, create/update list with original dict key
code:
import collections
d3 = collections.defaultdict(list)
for k,v in sorted(d.items()):
for vi in v:
d3[vi].append(k) # create list or append to existing list
print(dict(d3))
result:
{'b': ['1', '2'], 'd': ['3'], 'c': ['2', '3'], 'a': ['1', '2']}
Solution 3:
data = [(key, value) for key, values in d.items() for value in values]
d2 = defaultdict(list)
for value, key in data:
d2[key].append(value)
print(key, value)
Solution 4:
Here is a solution I found 5 years ago
from operator import itemgetter
from itertools import groupby
d = {'1': ['a', 'c'],'2': ['a', 'b', 'c'], '3': ['b']}
d2 = {x: [t[1] for t in group] for (x, group) in groupby(sorted(((j, k) for k, v in d.items() for j in v), key=itemgetter(0)), key=itemgetter(0))}
# {'a': ['1', '2'], 'c': ['1', '2'], 'b': ['2', '3']}
Post a Comment for "Return A Dictionary With Keys For A Given Dictionary's Values And Vice Versa"