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?
CodePudding user response:
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
CodePudding user response:
You can use all()
like so:
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())
Test code:
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))
Output:
True False True True False