Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get keys correspond to a value in dictionary

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

like image 476
JuanPablo Avatar asked Dec 27 '11 23:12

JuanPablo


People also ask

Can you get the key of a dictionary with value?

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.


2 Answers

You want to invert the mapping:

As shown in this question

dict((v,k) for k, v in map.iteritems())
like image 144
Jonathon Reinhart Avatar answered Sep 21 '22 08:09

Jonathon Reinhart


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
like image 35
srgerg Avatar answered Sep 24 '22 08:09

srgerg