Posts Tagged ‘reverse dictionary’
invert/reverse key-value pairs in a hash
March 29, 2012
Leave a comment
Problem
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' }
Solution
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' }
Categories: python
invert dictionary, invert hash, key-value pairs, reverse dictionary, reverse hash