I have been trying to invert a Python dictionary, i.e. taking from an original dict all values, get a unique set and use these as keys for a new dict. Values for the new keys should be a list of the original dict's keys, which had the new dict key as value.
Certainly there are better ways, but I came up with:
myDict1 = {'foo0':'alpha','foo1':'alpha','bar0':'beta','bar4':'beta'}
tmpDict = dict.fromkeys(set(myDict1.values()),[])
for thingy in myDict1.keys():
tmpDict[myDict1[thingy]].append(thingy)
print(tmpDict)
giving tmpDict
as:
{'alpha': ['bar0', 'foo0', 'foo1', 'bar4'], 'beta': ['bar0', 'foo0', 'foo1', 'bar4']}
which is not the expected dict:
{'alpha': ['foo0', 'foo1'], 'beta': ['bar0', 'bar4']}
Where is the error?