Skip to content Skip to sidebar Skip to footer

Python: Modify A Dict To Make The Key A Value, And A Value The Key

Say I have a dictionary dict, with the following values: dict1 = {'1': ['a','b', 'c', 'd'], '2': ['e','f', 'g', 'h']} How would I make one of the values the key in a new dictionar

Solution 1:

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

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

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

edit As pointed out by Adrien Plisson, Python 3 does not support iteritems. Also, in Python 2.7+ and 3, one can use a dictionary comprehension:

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

Solution 2:

And yet another approach:

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

for k in dict1:

    dict2[dict1[k][-1]]= dict1[k]
    dict2[dict1[k][-1]][-1] = k

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

Solution 3:

make the key a value, and a value the key:

dict2 = dict( (dict1[key], key) forkeyin dict1 )

or

dict2 = dict( (value,key) for key, value in dict1.items() )

Both work for all versions of Python.


special case

Only in the special case of the example in the question this does not work, because a list cannot be used as a key. So using the last element of each list as key and replacing this last element with the previous key, we get the more complicated:

dict2 = dict( (dict1[key][-1], dict1[key][:-1]+[key]) forkeyin dict1 )

Note that from Python 3.0, dict.iterkeys(), dict.itervalues(), and dict.iteritems() are no longer valid. dict.keys(), dict.values(), and dict.items() are OK. Just iterating over a dict (as in for key over dict1) returns the list of keys. Often used are sorted keys as in

keys = sorted(mydict)

Post a Comment for "Python: Modify A Dict To Make The Key A Value, And A Value The Key"