开发者

reversing dictionary in python [duplicate]

This question already has answers here: Closed 11 years ago.

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


  1. Convert dict to a list of (key, value) pairs with dict.items()
  2. Reversing each element of list with reversed() and map(): map(reversed, ... )
  3. Convert list of (key, value) pairs to dictionary: dict( ... )

    >>> d = {'a': 1, 'b': 2}
    >>> dict(map(reversed, d.items()))
    {1: 'a', 2: 'b'}
    
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜