Aug-31-2020, 09:20 AM
Hi all,
I was wondering if it was possible to rewrite the variants #1 #2 or #3 into a single line of code like variants #4 and #5?
I was wondering if it was possible to rewrite the variants #1 #2 or #3 into a single line of code like variants #4 and #5?
my_map = {'a': 3, 'c': 2, 'b': 2, 'e': 3, 'd': 1, 'f': 2}
#output = {3: ['a', 'e'], 2: ['c', 'b', 'f'], 1: ['d']}
#var1
inv_map = {}
for k, v in my_map.items():
inv_map[v] = inv_map.get(v, []) + [k]
print(inv_map)
#var2 (The best/fastest overall?)
inv_map2 = {}
for k, v in my_map.items():
inv_map2.setdefault(v, set()).add(k)
print(inv_map2)
#var3
inv_map3 = {}
for k, v in my_map.items():
inv_map3.setdefault(v, list()).append(k)
print(inv_map3)
#var4
print({v:[k for k in my_map.keys() if my_map[k] == v ] for k,v in my_map.items()})
#var5
print({v:[k for k in my_map if my_map[k] == v] for v in my_map.values()})
