1

I have hash:

test = {
    'a': ['localhost'],
    'b': ['bb','aa'],
    'c': ['cc']
}

For example I want to know key for bb ? (b).

Morvader
  • 2,317
  • 3
  • 31
  • 44
Bdfy
  • 23,141
  • 55
  • 131
  • 179
  • this might be of assistance: http://stackoverflow.com/questions/3282823/python-get-key-with-the-least-value-from-a-dictionary – Nope Mar 10 '11 at 14:52

3 Answers3

4

In general you can construct a reverse dictionary like this:

test_reversed = dict((v, k) for k, values in test.iteritems() for v in values)
Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
3

There's not an easy way to do this other than iterating over the keys and values. If you need to do this a lot, it would be worth constructing the reversed mapping as a one off, so you can just look up that:

from collections import defaultdict

reversed_test = defaultdict(set)
test = { 'a': ['localhost'], 'b': ['bb','aa'], 'c': ['cc'] }

for k, v in test.items():
    for i in v:
        reversed_test[i].add(k)

print reversed_test['bb']

The reversed_test dictionary maps a key such as 'bb' to a set of strings that originally mapped to lists containing 'bb'. This is much less concise than Space_C0wb0y's neat solution since I was assuming it might be possible for test to look like:

{'a': ['foo','bar','foo'], 'b': ['foo','quux'] }

In other words:

  • multiple keys might map to lists containing 'foo'
  • 'foo' might appear multiple times in a list.
Community
  • 1
  • 1
Mark Longair
  • 446,582
  • 72
  • 411
  • 327
2

Assuming there is exactly one key matching, you can use

key = next(k for k in test if "bb" in test[k])

This iterates over all keys until the assigned list contains what you are looking for. This operation is much less efficient than the lookup by key, which is what dictionaries are made for.

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841