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 ().
source share