如何检查Python字典中是否存在多个值

1 python dictionary

我有一本看起来像这样的字典:

word_freq = {
"Hello": 56,
"at": 23,
"test": 43,
"this": 78
Run Code Online (Sandbox Code Playgroud)

}

和值列表list_values = [val1, val2]

我需要检查所有values: val1 and val2in是否list_values作为 dict 中的值存在word_freq

我尝试用 is 函数解决问题:

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
Run Code Online (Sandbox Code Playgroud)

必须有一个简单的方法来做到这一点,但我对 python 还是新手,无法弄清楚。尝试了 word_freq 中的 Booth 值是否不起作用。

Tim*_*rts 5

这应该做你想要的:

def check_value_exist(test_dict, value1, value2):
    return all( v in test_dict for v in [value1,value2] ) 
Run Code Online (Sandbox Code Playgroud)

  • 是的,这将是一个更灵活的解决方案。有时我会犹豫是否要在学校作业中提出先进的技术。 (2认同)