-2

Say I have a dictionary:

d = {
    0: ('f', 'farm'),
    1: ('m', 'mountain'),
    2: ('h', 'house'),
    3: ('t', 'forest'),
    4: ('d', 'desert')
}

and the only information I'm given is the value h. How can I retrieve 2 - the key that corresponds to h - from the dictionary?

In other words, I don't have the whole tuple ('h', 'house') to do a proper reverse lookup, I only have the h. Is there an elegant way to do this?

Grav
  • 461
  • 6
  • 18
  • What happens if you have repeated `'h'` values? – Dani Mesejo Sep 15 '21 at 06:54
  • 2
    Does this answer your question? [Reverse lookup dict of tuples, or use a different data structure?](https://stackoverflow.com/questions/69188105/reverse-lookup-dict-of-tuples-or-use-a-different-data-structure) – no comment Sep 15 '21 at 06:55
  • If it's an infrequent operation where you don't need to build a permanent reverse lookup table, `next((idx for (idx, entry) in d if entry[0] == 'h'), None)` should be okay. – Amadan Sep 15 '21 at 06:56
  • Why are you asking the same question again. – PCM Sep 15 '21 at 07:02

1 Answers1

0
for k, v in d.items():
    if v[0] == 'h':
        print(k)