-1

If p='hello' I need to search the dictionary for the value 'hello' and return the key for 'hello' Is there a certain built in function that could help me do this?

user3527972
  • 89
  • 2
  • 7

2 Answers2

1

I can't think of a built-in function to do this, but the best possible way would be:

def get_keys(d, x):
    return [k for k, v in adict.items() if v == x]

Demo:

>>> example = {'baz': 1, 'foo': 'hello', 'bar': 4, 'qux': 'bye'}
>>> get_keys(example, 'hello')
['foo']

We use a list here because any one value can occur multiple times in a dictionary- so we need something to hold all of the applicable corresponding keys.

With that in mind, if you only want the first found instance you would just do [0] on the returned list.

anon582847382
  • 19,907
  • 5
  • 54
  • 57
0

You can do:

def get_pos(my_dict, my_str):
    pos = []
    for i in my_dict:
        if my_dict[i] == my_str:
        pos.append(i)
    return pos

Examples

>>> a = {'apple':'hello', 'banana':'goodbye'}
>>> get_pos(a,'hello')
'apple'
sshashank124
  • 31,495
  • 9
  • 67
  • 76