Posts Tagged ‘key-value pairs’

invert/reverse key-value pairs in a hash

March 29, 2012 Leave a comment

You have a hash (dictionary) and you want to invert/reverse the key-value pairs. Example:

# input
map = { 'a': 1, 'b':2 }
# output
{ 1: 'a', 2: 'b' }


map = dict((v,k) for k, v in map.iteritems())

This tip is from here.

Use Case
Currently I’m working on a small application that helps one to learn new words. Reversing the dictionary of words, you can practice in both directions:

# English to Hungarian
{ 'fox': 'róka', 'hunter': 'vadász' }
# Hungarian to English
{ 'róka': 'fox', 'vadász': 'hunter' }