Reputation: 55
I have a dictionary with unique values and I want to invert it (i.e. swap keys with values) inplace. Is there any way doing it without using another dictionary?
I would prefer to just manipulate the items inside the dict than use a new dictionary, so that id(my_dict)
would remain the same.
Upvotes: 1
Views: 951
Reputation: 22001
If you are trying to swap keys and values and do not mind duplicate values creating key conflicts, you can "reverse" the dictionary rather easily with a single line of code:
dictionary = dict(map(reversed, dictionary.items()))
If you would rather use the dictionary comprehension syntax instead, you can write this line:
dictionary = {value: key for key, value in dictionary.items()}
If you do not want to use the items
method of the dictionary, it is rather easy to avoid:
dictionary = {dictionary[key]: key for key in dictionary}
If you can afford creating a copy of the dictionary, you can reverse it in place if needed:
def reverse_in_place(dictionary):
reference = dictionary.copy()
dictionary.clear()
dictionary.update(map(reversed, reference.items()))
Upvotes: 2
Reputation: 2793
I guess you want to swap the keys and the values of the dict?
You can do it like this:
dict_name = dict(zip(dict_name.values(), dict_name.keys()))
Upvotes: 0