Maus Maus - 10 months ago 39
Python Question

better one-liner to flip keys and values of a dictionary

I've written a one-liner to accomplish this:

vocab_tag = dict(zip(*reversed(zip(*tag_vocab.items()))))

Can anybody write one that's more comprehensible/direct?


A readable and short dict comprehension is probably the best one can do:

vocab_tage = {value: key for key, value in tag_vocab.items()}

Pre 2.7, dictionary comprehensions don't exist, but we can replace them trivially with dict() and a generator expression:

vocab_tage = dict((value, key) for key, value in tag_vocab.items())

It's worth noting that this presumes there are no keys with the same value (as does the example in the question).