'How to check if multiple values exists in a dictionary python
I have a dictionary that looks like that:
word_freq = {
"Hello": 56,
"at": 23,
"test": 43,
"this": 78
}
and a list of values list_values = [val1, val2]
I need to check that all the values: val1 and val2 in list_values exist as values in word_freq dict.
I tried to solve the problem withis function:
def check_value_exist(test_dict, value1, value2):
list_values = [value1, value2]
do_exist = False
for key, value in test_dict.items():
for i in range(len(list_values)):
if value == list_values[i]:
do_exist = True
return do_exist
There must be a straightforward way to do it, but i'm still new to python and can't figure it out. tried if booth values in word_freq, didn't work.
Solution 1:[1]
This should do what you want:
def check_value_exist(test_dict, value1, value2):
return all( v in test_dict for v in [value1,value2] )
Solution 2:[2]
Make values a set and you can use set.issubset to verify all values are in the dict:
def check_value_exist(word_freq, *values):
return set(values).issubset(word_freq)
print(check_value_exists(word_freq, 'at', 'test'))
print(check_value_exists(word_freq, 'at', 'test', 'bar'))
True
False
Solution 3:[3]
One approach:
def check_value_exist(test_dict, value1, value2):
return {value1, value2} <= set(test_dict.values())
print(check_value_exist(word_freq, 23, 56))
print(check_value_exist(word_freq, 23, 42))
Output
True
False
Since you receive the values as parameters you could build a set and verify that the set is a subset of the dict values.
If you are checking for keys, instead of values this should be enough:
def check_value_exist(test_dict, value1, value2):
return {value1, value2} <= test_dict.keys()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tim Roberts |
| Solution 2 | Jab |
| Solution 3 |
