检查是否可以在 Python 字典中找到键值组合

Check if key-value combinations can be found in Python dict

我正在寻找一个函数 found_in_color_dict(),它告诉我是否可以在 color_dict 中找到某个键​​值组合。函数returns分别为True或False。

color_dict = {"a":"blue", "b":"green", "c":"yellow", "d":"red", "e":"black", "f":"white"}

checkpoints_1 = {"a":"blue"}
checkpoints_2 = {"a":"green"}
checkpoints_3 = {"a":"blue", "d":"red"}
checkpoints_4 = {"a":"blue", "d":"red", "f":"white"}
checkpoints_5 = {"a":"blue", "d":"red", "f":"purple"}

根据示例,我希望得到以下结果:

found_in_color_dict(checkpoints_1)
>>> True

found_in_color_dict(checkpoints_2)
>>> False

found_in_color_dict(checkpoints_3)
>>> True

found_in_color_dict(checkpoints_4)
>>> True

found_in_color_dict(checkpoints_5)
>>> False

我只能想到复杂的方法来解决这个问题。但我想可能有一种简单的方法可以解决它,对吗?

您可以像这样使用 all()

color_dict = {"a":"blue", "b":"green", "c":"yellow", "d":"red", "e":"black", "f":"white"}
def found_in_color_dict(d):
    global color_dict
    return all(i in color_dict.items() for i in d.items())

测试代码:

checkpoints_1 = {"a":"blue"}
checkpoints_2 = {"a":"green"}
checkpoints_3 = {"a":"blue", "d":"red"}
checkpoints_4 = {"a":"blue", "d":"red", "f":"white"}
checkpoints_5 = {"a":"blue", "d":"red", "f":"purple"}

print(found_in_color_dict(checkpoints_1),
found_in_color_dict(checkpoints_2),
found_in_color_dict(checkpoints_3),
found_in_color_dict(checkpoints_4),
found_in_color_dict(checkpoints_5))

输出:

True False True True False

您可以使用 set.issubset:

注:dict.itemview作为集合

def found_in_color_dict(checkpoint):
    return checkpoint.items() <= color_dict.items()

>>> found_in_color_dict(checkpoints_1)
True
>>> found_in_color_dict(checkpoints_2)
False
>>> found_in_color_dict(checkpoints_3)
True
>>> found_in_color_dict(checkpoints_4)
True
>>> found_in_color_dict(checkpoints_5)
False