Given a dictionary like so:
my_map = {\'a\': 1, \'b\': 2}
How can one invert this map to get:
inv_map = {1: \'a\', 2: \'b\'
We can also reverse a dictionary with duplicate keys using defaultdict
:
from collections import Counter, defaultdict
def invert_dict(d):
d_inv = defaultdict(list)
for k, v in d.items():
d_inv[v].append(k)
return d_inv
text = 'aaa bbb ccc ffffd aaa bbb ccc aaa'
c = Counter(text.split()) # Counter({'aaa': 3, 'bbb': 2, 'ccc': 2, 'ffffd': 1})
dict(invert_dict(c)) # {1: ['ffffd'], 2: ['bbb', 'ccc'], 3: ['aaa']}
See here:
This technique is simpler and faster than an equivalent technique using
dict.setdefault()
.