Reputation: 594
How to get the key from a given value in a Python dictionary?
For example, if I have:
d = {
'Italy' : ['IT', 'ITA'],
'Austria' : ['AT'],
}
search = 'ITA'
What code is needed if I want this to return Italy. Notice that values can be lists
So if I search for AT, it should return Austria.
IT or ITA should return Italy.
Thanks in advance
Upvotes: 0
Views: 118
Reputation: 18924
Possible duplicate of Get key by value in dictionary but you could invert the dictionary with this code:
d_inv = {}
for k, v in d.items():
for i in v:
d_inv[i] = k
And then use:
d_inv[search]
Upvotes: 1