switching keys and values in a dictionary in pytho

2019-01-08 11:12发布

问题:

Say I have a dictionary like so:

my_dict = {2:3, 5:6, 8:9}

Is there a way that I can switch the keys and values to get:

{3:2, 6:5, 9:8}

回答1:

my_dict2 = dict((y,x) for x,y in my_dict.iteritems())

If you are using python 2.7 or 3.x you can use a dictionary comprehension instead:

my_dict2 = {y:x for x,y in my_dict.iteritems()}

Edit

As noted in the comments by JBernardo, for python 3.x you need to use items instead of iteritems



回答2:

Use this code (trivially modified) from the accepted answer at Python reverse / invert a mapping:

dict((v,k) for k, v in my_dict.iteritems())

Note that this assumes that the values in the original dictionary are unique. Otherwise you'd end up with duplicate keys in the resulting dictionary, and that is not allowed.

And, as @wim points out, it also assumes the values are hashable. See the Python glossary if you're not sure what is and isn't hashable.



回答3:

Try this:

my_dict = {2:3, 5:6, 8:9}

new_dict = {}
for k, v in my_dict.items():
    new_dict[v] = k


回答4:

maybe:

flipped_dict = dict(zip(my_dict.values(), my_dict.keys()))



回答5:

Sometimes, the condition that the values are all unique will not hold, in which case, the answers above will destroy any duplicate values.

The following rolls the values that might be duplicates up into a list:

from itertools import count
dict([(a,[list(d.keys())[i] for i,j in zip(count(), d.values())if j==a in set(d.values())])

I'm sure there's a better (non-list-comp) method, but I had a problem with the earlier answers, so thought I'd provide my solution in case others have a similar use-case.

P.S. Don't expect the dict to remain neatly arranged after any changes to the original! This method is a one-time use only on a static dict - you have been warned!



回答6:

my_dict = { my_dict[k]:k for k in my_dict}


回答7:

First of all it is not guaranteed that this is possible, since the values of a dictionary can be unhashable.

In case these are not, we can use a functional approach with:

reversed_dict = dict(map(reversed, original_dict.items()))


回答8:

If the values are not unique this will collide the key space in conversion. Best is to keep the keys in list when switching places

below handles this -

RvsD = dict()
for k,v in MyDict.iteritems():
    RsvD.setdefault(v, []).append(k)