6

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()]) 

2 Answers 2

8

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))) 
Sign up to request clarification or add additional context in comments.

Comments

0

Here is a simple and direct implementation of inverting a dictionary and keeping the larger 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 tightened-up a bit 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 an approach using sorted().

1 Comment

"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."

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.