This is not simple, dictionary reversing. You also need to access/create the inner list and populate it accordingly (while avoiding key clashing on the resulting dict).
One way of doing this is:
def reverse_dict_special(d):
result = {}
for k, vs in d.items():
for v in vs:
if v in result:
result[v].append(k)
else:
result[v] = [k]
return result
d = {'move': ['liikuttaa'], 'hide': ['piilottaa', 'salata'], 'six': ['kuusi'], 'fir': ['kuusi']}
reverse_dict_special(d)
# {'liikuttaa': ['move'],
# 'piilottaa': ['hide'],
# 'salata': ['hide'],
# 'kuusi': ['six', 'fir']}
Note that this does not require the use of collections.defaultdict
or using dict.setdefault()
as proposed by @PeterWood.
Indeed the proposed method seems to get to faster results then both the other two:
from collections import defaultdict
def reverse_dict_special2(d):
result = defaultdict(list)
for key, values in d.items():
for value in values:
result[value].append(key)
return result
def reverse_dict_special3(d):
result = {}
for key, values in d.items():
for value in values:
result.setdefault(value, []).append(key)
return result
%timeit reverse_dict_special(d)
# 1.22 µs ± 29.8 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%timeit reverse_dict_special2(d)
# 2.04 µs ± 44 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%timeit reverse_dict_special3(d)
# 1.55 µs ± 18.6 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
(EDITED: I had misunderstood the question at first, and did not realize that the input inner lists may have had multiple items)