0

So I want to go over a dictionary searching for the value True. If it finds it, I'd like to return the Key that matched with the value.

I tried using d.get(True) but that returns all of the keys. I only need the first one it could find.

Any ideas how to do so?

Thanks

Daniel
  • 621
  • 5
  • 22

2 Answers2

0

Just loop over the dictionary with for

d = {...}

for i in d:
    if d[i]:
        return i

That, or the dictionary should be "backwards" to what you are using. That would be the correct way of using a dictionary.

d = {True: [...], False: [...]}
ofthegoats
  • 295
  • 4
  • 10
0

you could create a reverse lookup dictionary:

from collections import defaultdict

dct = {a: bool(a & 1) for a in range(7)}
# {0: False, 1: True, 2: False, 3: True, 4: False, 5: True, 6: False}

rev = defaultdict(list)
for key, value in dct.items():
    rev[value].append(key)
# defaultdict(<class 'list'>, {False: [0, 2, 4, 6], True: [1, 3, 5]})

now rev[True] would return all the previous keys that had True as value.

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111