我有一个python字典,它包括200个键,每个键有长字符串和几行作为值
字典示例
var_holder = {
"text0": 'MontgomerynnBirmingham Juneau. PhoenixnnSacramento ,nChicagonnSpringfield: Atlantanx0c'
}
我需要什么检查这些值是否包含某个单词
我做了什么
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": 'MontgomerynnBirmingham Juneau. PhoenixnnSacramento ,nChicagonnSpringfield: Atlantanx0c'
}
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": 'MontgomerynnBirmingham Juneau. PhoenixnnSacramento ,nChicagonnSpringfield: Atlantanx0c'
}
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": 'MontgomerynnBirmingham Juneau. PhoenixnnSacramento ,nChicagonnSpringfield: Atlantanx0c'
}
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")