0

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?

THX
  • 553
  • 2
  • 8
  • 18
  • Why do you have `set(myDict1.keys())`? `for thingy in myDict1` would behave identically. – jonrsharpe Jul 11 '16 at 15:47
  • That one is probably just a remnant while trying to get it working and moving stuff around - I see no reason why I added it there right now. I have edited the question. Thanks for pointing to the previous question! Good to know about the referencial behaviour of `fromkeys()` etc.! – THX Jul 12 '16 at 07:19

1 Answers1

1

When you use fromkeys, all the keys point to the same object. In this case a list:

dict.fromkeys(set(myDict1.values()),[])

I would suggest using:

dict((k, []) for k in set(myDict1.values()))

Which would create a new list for each key.

Dan D.
  • 73,243
  • 15
  • 104
  • 123