I am looking for a function found_in_color_dict()
which tells me if a certain key-value combination can be found in color_dict
. The function returns True or False, respectively.
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"}
Based on the example I would expect the following results:
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
I can only think of complex approaches to solve this problem. But I guess there might be an easy way to solve it, right?
Advertisement
Answer
You can use set.issubset
:
Note: dict.itemview
acts as a set
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