Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inverting Dictionaries in Python

I want to know which would be an efficient method to invert dictionaries in python. I also want to get rid of duplicate values by comparing the keys and choosing the larger over the smaller assuming they can be compared. Here is inverting a dictionary:

inverted = dict([[v,k] for k,v in d.items()])
like image 273
Salazar Avatar asked Oct 20 '11 00:10

Salazar


People also ask

What is inverting a dictionary in python?

Reversing a dictionary is different from reversing a list, it means to invert or switch the key and value elements of the dictionary, essentially swapping them for whatever purpose the developer might use it for.

Can dictionaries be reversed in Python?

Later you make use of a reversed() function which is an in-built python method that takes an argument as the sequence data types like tuple, lists, dictionaries, etc and returns the reverse of it. Remember that reversed() method does not modify the original iterator.

How do you reverse the order of a dictionary in python?

Use dict. items() to get a list of tuple pairs from d and sort it using a lambda function and sorted(). Use dict() to convert the sorted list back to a dictionary. Use the reverse parameter in sorted() to sort the dictionary in reverse order, based on the second argument.


1 Answers

To remove duplicates by using the largest key, sort your dictionary iterator by value. The call to dict will use the last key inserted:

import operator
inverted = dict((v,k) for k,v in sorted(d.iteritems(), key=operator.itemgetter(1)))
like image 79
Alan Post Avatar answered Oct 21 '22 05:10

Alan Post