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
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
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
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)
.
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
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']
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.