0

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

Tadeo Rod
  • 574
  • 5
  • 11
  • Possible duplicate of [Get key by value in dictionary](https://stackoverflow.com/questions/8023306/get-key-by-value-in-dictionary) – Taxellool Jul 09 '17 at 03:12

1 Answers1

1

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]
Anton vBR
  • 18,287
  • 5
  • 40
  • 46
  • Thanks, this really helped. I was checking the original link of my duplicate, and that would have worked if no list were present in the values. – Tadeo Rod Jul 09 '17 at 00:57