Home > python > invert/reverse key-value pairs in a hash

invert/reverse key-value pairs in a hash

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' }
About these ads
  1. No comments yet.
  1. No trackbacks yet.
You must be logged in to post a comment.

Get every new post delivered to your Inbox.

Join 61 other followers

%d bloggers like this: