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

invert/reverse key-value pairs in a hash

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' }
About these ads
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 65 other followers

%d bloggers like this: