I have hash:
test = {
'a': ['localhost'],
'b': ['bb','aa'],
'c': ['cc']
}
For example I want to know key for bb ? (b).
I have hash:
test = {
'a': ['localhost'],
'b': ['bb','aa'],
'c': ['cc']
}
For example I want to know key for bb ? (b).
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)
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:
'foo'
'foo'
might appear multiple times in a list.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.