Home > Enterprise >  How to check if multiple values exists in a dictionary python
How to check if multiple values exists in a dictionary python

Time:11-05

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.

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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()
  • Related