1

Possible Duplicate:
Python reverse / inverse a mapping
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

Community
  • 1
  • 1
user899714
  • 455
  • 6
  • 13
  • 23

4 Answers4

10
dictb = dict ( (v,k) for k, v in dicta.items() )
rocksportrocker
  • 7,251
  • 2
  • 31
  • 48
  • Why do I get `TypeError: unhashable type: 'dict' ` when running this line? My *dicta* is called `G.node` and comes from the `networkx` package. – FaCoffee Oct 20 '15 at 16:52
  • 1
    I guess at least one of the values of `dicta` is a Python dictionary or is a nested data structure containing one. When constructing `dictb` you try to use an unhashable data structure as a key which is not allowed in Python. – rocksportrocker Oct 21 '15 at 08:46
  • So yes, my *dicta* is actually a dictionary of dictionaries. Does this mean that I cannot reverse it because of some (or all) of its elements being *unhashable*? – FaCoffee Oct 21 '15 at 17:36
  • Yes. You have some unhashable values in your primary dictionary, and when you want to revert them those become keys. – rocksportrocker Oct 21 '15 at 21:08
  • What is your current use case ? – rocksportrocker Oct 21 '15 at 21:09
  • Well it's hard to explain in a few chars. I'd better ask to turn this into a chat. It is possible? The problem btw relates to the use of the `networkx` package. The dict of dicts I am referring to is the one that tells me for each node what are its connections. – FaCoffee Oct 22 '15 at 16:10
  • So the node is the key and the dict of its connections is the value. – FaCoffee Oct 22 '15 at 16:22
1

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
Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
1

Try this:

dicatb = {}
for x,k in dicta.iteritems():
    dictab[k] = x
freakish
  • 54,167
  • 9
  • 132
  • 169
1
  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'}
    
Ski
  • 14,197
  • 3
  • 54
  • 64