【问题标题】:How to check if multiple values exists in a dictionary python如何检查字典python中是否存在多个值
【发布时间】:2021-12-19 02:09:38
【问题描述】:

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

word_freq = {
"Hello": 56,
"at": 23,
"test": 43,
"this": 78

}

还有一个值列表list_values = [val1, val2]

我需要检查list_values 中的所有values: val1 and val2 是否作为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

必须有一个简单的方法来做到这一点,但我还是 python 的新手,无法弄清楚。如果 word_freq 中的展位值无效,请尝试。

【问题讨论】:

  • exist = all( v in test_dict for v in [value1,value2] )
  • 查找all(...)
  • 您是在检查值还是键?从代码和问题文本看来是值。

标签: python dictionary


【解决方案1】:

这应该做你想做的:

def check_value_exist(test_dict, value1, value2):
    return all( v in test_dict for v in [value1,value2] ) 

【讨论】:

  • def check_value_exist(test_dict, *values): return all( v in test_dict for v in values) 怎么样?
  • 是的,这将是一个更灵活的解决方案。我有时会犹豫在可能是学校作业的情况下建议先进的技术。
【解决方案2】:

values 设为一个集合,您可以使用set.issubset 验证所有值都在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

【讨论】:

    【解决方案3】:

    一种方法:

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

    输出

    True
    False
    

    由于您收到作为参数的值,因此您可以构建一个集合并验证该集合是 dict 值的子集。

    如果您正在检查键,而不是值,这应该足够了:

    def check_value_exist(test_dict, value1, value2):
        return {value1, value2} <= test_dict.keys()
    

    【讨论】:

      猜你喜欢
      • 2012-01-03
      • 2021-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-16
      • 2012-03-27
      • 2016-03-20
      相关资源
      最近更新 更多