Python: Modify a dict to make the key a value, and a value the key -


say have dictionary dict, following values:

dict1 = {'1': ['a','b', 'c', 'd'], '2': ['e','f', 'g', 'h']} 

how make 1 of values key in new dictionary, dict1?

dict2 = {'d': ['a','b', 'c', '1'], 'h': ['e','f', 'g', '2']} 

in [12]: d = {'1': ['a','b', 'c', 'd'], '2': ['e','f', 'g', 'h']}  in [13]: dict((v[-1],v[:-1]+[k]) k,v in d.iteritems()) out[13]: {'d': ['a', 'b', 'c', '1'], 'h': ['e', 'f', 'g', '2']} 

k original key, v original value (the list). in result, v[-1] becomes new key , v[:-1]+[k] becomes new value.

edit pointed out adrien plisson, python 3 not support iteritems. also, in python 2.7+ , 3, 1 can use dictionary comprehension:

{v[-1]: v[:-1]+[k] k,v in d.items()} # python 2.7+ 

Comments

Popular posts from this blog

linux - Using a Cron Job to check if my mod_wsgi / apache server is running and restart -

actionscript 3 - TweenLite does not work with object -

jQuery Ajax Render Fragments OR Whole Page -