Inverting Dictionaries in Python

I want to know what would be an efficient method for converting dictionaries into python. I also want to get rid of duplicate values ​​by comparing the keys and choosing larger ones compared to smaller ones, assuming that they can be compared. The dictionary is inverted here:

inverted = dict([[v,k] for k,v in d.items()]) 
+6
source share
2 answers

To remove duplicates using the largest key, assemble the iterator dictionary by value. The dict call will use the last key entered:

 import operator inverted = dict((v,k) for k,v in sorted(d.iteritems(), key=operator.itemgetter(1))) 
+8
source

Here is a simple and direct implementation of inverting a dictionary and storing more of any duplicate values:

 inverted = {} for k, v in d.iteritems(): if v in inverted: inverted[v] = max(inverted[v], k) else: inverted[v] = k 

This can be a bit compressed with dict.get ():

 inverted = {} for k, v in d.iteritems(): inverted[v] = max(inverted.get(v, k), k) 

This code makes fewer comparisons and uses less memory than the approach using sorted ().

0
source

Source: https://habr.com/ru/post/899654/


All Articles