Swapping Keys for Values in a Dictionary


myDictionary = {'color':'blue', 'speed':'fast',  'number':1, 5:'number'} swapDictionary = {} for key, val in myDictionary.iteritems():     swapDictionary[val] = key

Currently, there is not a method in Python to swap around the keys and values. However, this can be very useful if you are using a dictionary in which you may frequently need to look up items by value. Rather than searching through the entire dictionary each time, you could create an alternative dictionary that has the values swapped.

To swap the keys and values in a dictionary, simply iterate through the items in the dictionary using the iteritems method and use the values as keys assigning the original key as the value.

Note

The values must be of legal key types for the keys and values to be swapped.


myDictionary = {'color':'blue', 'speed':'fast',  'number':1, 5:'number'} print myDictionary #Swap keys for values swapDictionary = {} for key, val in myDictionary.iteritems():     swapDictionary[val] = key print swapDictionary


swap_dict.py

{'color': 'blue', 'speed': 'fast',  'number': 1, 5: 'number'} {'blue': 'color', 1: 'number',  'number': 5, 'fast': 'speed'}


Output of swap_dict.py




Python Phrasebook(c) Essential Code and Commands
Python Phrasebook
ISBN: 0672329107
EAN: 2147483647
Year: N/A
Pages: 138
Authors: Brad Dayley

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net