无法检查字典中是否存在字符串 [python]

cant check if a string exists in a dictionary [python]

我在 python 中有一个字典,它包含 200 个键,每个键都有很长的字符串和几行作为值

字典示例

var_holder = {
    "text0": 'Montgomery\n\nBirmingham Juneau. Phoenix\n\nSacramento ,\nChicago\n\nSpringfield: Atlanta\n\x0c'
}

我需要什么 检查这些值是否包含某个词

我做了什么

value = 'Phoenix'
if any([True for k,v in var_holder.items() if v == value]):
    print(f"Yes, Value: '{value}' exists in dictionary")
else:
    print(f"No, Value: '{value}' does not exists in dictionary")

输出 否,值:'Phoenix' 不存在于字典中

预期输出 是的,值:'Phoenix' 确实存在于字典中

有人可以更正我的代码吗? 或者建议另一种方法

您应该使用 in 在字符串中查找值而不是 == 比较。

var_holder = {
    "text0": 'Montgomery\n\nBirmingham Juneau. Phoenix\n\nSacramento ,\nChicago\n\nSpringfield: Atlanta\n\x0c'
}

value = 'Phoenix'
if any(value in v for v in var_holder.values()):
    print(f"Yes, Value: '{value}' exists in dictionary")
else:
    print(f"No, Value: '{value}' does not exists in dictionary")

我建议您这样做:

var_holder = {
    "text0": 'Montgomery\n\nBirmingham Juneau. Phoenix\n\nSacramento ,\nChicago\n\nSpringfield: Atlanta\n\x0c'
}

value = 'Phoenix'
gen = (v for v in var_holder.values() if value in v)

if gen:
    print(f"Yes, Value: '{value}' exists in dictionary")
else:
    print(f"No, Value: '{value}' does not exists in dictionary")

看看这个

var_holder = {
    "text0": 'Montgomery\n\nBirmingham Juneau. Phoenix\n\nSacramento ,\nChicago\n\nSpringfield: Atlanta\n\x0c'
    }

value = 'Phoenix'
if any(value in x for x in var_holder.values()):
    print(f"Yes, Value: '{value}' exists in dictionary")
else:
    print(f"No, Value: '{value}' does not exists in dictionary")