I have this dictionary in python
d={1: 'a', 2: 'b', 3: 'c'}
with d[1] I get
>>> d[1]
'a'
how I can get the key correspond to a value ?
example : with 'a' get 1
Method 3: Get the key by value using dict.item() We can also fetch the key from a value by matching all the values using the dict.item() and then print the corresponding key to the given value.
You want to invert the mapping:
As shown in this question
dict((v,k) for k, v in map.iteritems())
You could create a new dictionary from the keys and values in the initial one:
>>> d2 = dict((v, k) for k, v in d.iteritems())
>>> d2
{'a': 1, 'c': 3, 'b': 2}
>>> d2['a']
1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With