I receive a dictionary as input, and would favor to to rerotate a dictionary whose tricks will certainly be the input"s values and whose worth will certainly be the equivalent input tricks. Values are unique.

You watching: Swap keys and values in dictionary python

For example, say my input is:

a = dict()a<"one">=1a<"two">=2I would choose my output to be:

1: "one", 2: "two"To clarify I would prefer my result to be the indistinguishable of the following:

res = dict()res<1> = "one"res<2> = "two"Any neat Pythonic method to accomplish this?






From Python 2.7 on, including 3.0+, there"s an arguably shorter, even more readable version:

In <1>: my_dict = "x":1, "y":2, "z":3Python 3In <2>: dict((value, key) for crucial, value in my_dict.items())Out<2>: 1: "x", 2: "y", 3: "z"Python 2In <2>: dict((worth, key) for vital, value in my_dict.iteritems())Out<2>: 1: "x", 2: "y", 3: "z"
You deserve to manipulate dict comprehensions:

Python 3

res = v: k for k, v in a.items()Python 2res = v: k for k, v in a.iteritems()Edited: For Python 3, use a.items() rather of a.iteritems(). Discussions about the differences in between them can be discovered in iteritems in Python on SO.

The present leading answer assumes values are unique which is not constantly the situation. What if values are not unique? You will loose information!For example:

d = "a":3, "b": 2, "c": 2 v:k for k,v in d.iteritems() retransforms 2: "b", 3: "a".

The indevelopment about "c" was entirely ignored.Ideally it need to had actually be somepoint prefer 2: <"b","c">, 3: <"a">. This is what the bottom implementation does.

Python 2.x

def reverse_non_unique_mapping(d): dinv = for k, v in d.iteritems(): if v in dinv: dinv.append(k) else: dinv = return dinv

Python 3.x

def reverse_non_unique_mapping(d): dinv = for k, v in d.items(): if v in dinv: dinv.append(k) else: dinv = return dinv
You might try:

Python 3

d="one":1,"two":2d2=dict((worth,key) for essential,worth in d.items())d2 "two": 2, "one": 1Python 2d="one":1,"two":2d2=dict((value,key) for crucial,value in d.iteritems())d2 "two": 2, "one": 1Beware that you cannot "reverse" a dictionary if

More than one key shares the exact same worth. For instance "one":1,"two":1. The brand-new dictionary have the right to only have one item with essential 1.One or even more of the worths is unhashable. For example "one":<1>. <1> is a valid value yet not a valid essential.

See more: Orphan 8 Book Review - Book Review: Orphan #8, By Kim Van Alkemade

See this threview on the python mailing list for a conversation on the subject.

new_dict = dict( (my_dict, k) for k in my_dict)or also better, yet only works in Python 3:

new_dict = my_dict: k for k in my_dict
Anvarious other way to expand also on Ilya Prokin"s response is to actually usage the reversed attribute.

dict(map(reversed, my_dict.items()))In significance, your dictionary is iterated with (utilizing .items()) wright here each item is a key/value pair, and those items are swapped via the reversed attribute. When this is passed to the dict constructor, it transforms them into value/crucial pairs which is what you want.

Suggestion for an innovation for Javier answer :

dict(zip(d.values(),d))Instead of d.keys() you deserve to compose just d, bereason if you go through dictionary with an iterator, it will certainly rerotate the secrets of the pertinent dictionary.

Ex. for this habits :

d = "a":1,"b":2for k in d: k"a""b"
dict(map(lambda x: x<::-1>, YourDict.items())).items() returns a list of tuples of (key, value). map() goes via facets of the list and also uses lambda x:<::-1> to each its aspect (tuple) to reverse it, so each tuple becomes (value, key) in the new list spitted out of map. Finally, dict() provides a dict from the new list.

Hanan"s answer is the correct one as it covers even more basic situation (the various other answers are type of misleading for someone unmindful of the duplicate situation). An development to Hanan"s answer is using setdefault:

Using loop:-

newdict = #Will contain reversed key:value pairs.for key, worth in zip(my_dict.keys(), my_dict.values()): # Operations on key/worth deserve to additionally be percreated. newdict = vital
Adding an in-location solution:

I discover this variation the many thorough one:

a = 1: "one", 2: "two"

swapped_a = value : essential for vital, worth in a.items()


output :"one": 1, "two": 2

Highly energetic question. Earn 10 reputation (not counting the association bonus) in order to answer this question. The reputation necessity helps defend this question from spam and also non-answer task.

Not the answer you're looking for? Browse other questions tagged python dictionary or ask your own question.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev2021.9.2.40142

Your privacy

By clicking “Accept all cookies”, you agree Stack Exreadjust deserve to store cookies on your tool and discshed indevelopment in accordance through our Cookie Policy.