3
 dic = {'key1': ["value1",  "value2"],
        'key2': ["value4", "value5"] }

 "value4" in [x for v in dic.values() for x in v]
 >> True

I want to print the key for value4 instead of True

5 Answers5

2

A python dictionary is optimized for accessing value by key, not the reverse, so here you have no better option than to iterate over all entries in the dict:

for key, values in dic.items():
    if 'value4' in values:
        print(key)
        break
Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176
  • for only one value above code will work, if multiple values are present then we have to loop as mentioned below –  Jul 09 '18 at 11:53
  • The way I understand the question, we are searching with a single value. This approach will also work for more than one value but will be sub optimal if there are multiple queries as pointed out in some of the other answers – Ivaylo Strandjev Jul 09 '18 at 11:55
1

For an isolated call, you should iterate dic and break as per @IvayloStrandjev's solution.

For repeated calls, it's a good idea to reverse your dictionary to maintain O(1) lookup complexity. Assuming your values are non-overlapping:

dic = {'key1': ["value1",  "value2"],
       'key2': ["value4", "value5"]}

dic_reverse = {w: k for k, v in dic.items() for w in v}

print(dic_reverse)

{'value1': 'key1', 'value2': 'key1', 'value4': 'key2', 'value5': 'key2'}

Then you can retrieve your key via dic_reverse.get('value4', None).

jpp
  • 159,742
  • 34
  • 281
  • 339
0

You can use filter.

dic = {'key1': ["value1",  "value2"],
        'key2': ["value4", "value5"] }
filter(lambda x: "value4" in dic[x], dic)         # python 2
list(filter(lambda x: "value4" in dic[x], dic))   # python 3
vishal
  • 1,081
  • 2
  • 10
  • 27
0

Using a list comprehension.

Ex:

dic = {'key1': ["value1",  "value2"],
        'key2': ["value4", "value5"] }
print( [k for k,v in dic.items() if "value4" in v])

Output:

['key2']
Rakesh
  • 81,458
  • 17
  • 76
  • 113
0

Not sure if you want this but here you go -

[k for k, v in dic.iteritems() for i in v if i == "value1"]

Let me know if this solves the problem.

Sushant
  • 3,499
  • 3
  • 17
  • 34
  • thanks, python3 dic.items [k for k, v in dic.items() for i in v if i == "value1"] –  Jul 09 '18 at 11:50