reversing dictionary in python [duplicate]
Possible Duplicate:
Python reverse / inverse a ma开发者_StackOverflowpping Swap keys for unique values in a dictionary in Python
Hello i want to understand how to reverse and compare dictionary values: for example :
if i have one dictionary with key:value format like this
dicta = [1:2, 9:8, 4:6, 3:2, 0:7, 1:34, 9:90, 1:8, 67:43, 54:23]
How do i reverse it such that values of dicta above become keys and keys become values like this:
dictb = [2:1, 8:9, 6:4, 2:3, 7:0, 34:1, 90:9, 8:1, 43:67, 23:54]
I am using python 2.5 pls help
dictb = dict ( (v,k) for k, v in dicta.items() )
The syntax for dictionaries is the following:
dicta = {1:2, 9:8}
This will do the conversion:
dictb = {}
for k in dicta:
dictb[dicta[k]] = k
Try this:
dicatb = {}
for x,k in dicta.iteritems():
dictab[k] = x
- Convert dict to a list of (key, value) pairs with dict.items()
- Reversing each element of list with reversed() and map():
map(reversed, ... )
Convert list of (key, value) pairs to dictionary:
dict( ... )
>>> d = {'a': 1, 'b': 2} >>> dict(map(reversed, d.items())) {1: 'a', 2: 'b'}
精彩评论