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()])
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.
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.
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.
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)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With