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.
JavaScript
x
8
1
color_dict = {"a":"blue", "b":"green", "c":"yellow", "d":"red", "e":"black", "f":"white"}
2
3
checkpoints_1 = {"a":"blue"}
4
checkpoints_2 = {"a":"green"}
5
checkpoints_3 = {"a":"blue", "d":"red"}
6
checkpoints_4 = {"a":"blue", "d":"red", "f":"white"}
7
checkpoints_5 = {"a":"blue", "d":"red", "f":"purple"}
8
Based on the example I would expect the following results:
JavaScript
1
15
15
1
found_in_color_dict(checkpoints_1)
2
>>> True
3
4
found_in_color_dict(checkpoints_2)
5
>>> False
6
7
found_in_color_dict(checkpoints_3)
8
>>> True
9
10
found_in_color_dict(checkpoints_4)
11
>>> True
12
13
found_in_color_dict(checkpoints_5)
14
>>> False
15
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
JavaScript
1
3
1
def found_in_color_dict(checkpoint):
2
return checkpoint.items() <= color_dict.items()
3
JavaScript
1
11
11
1
>>> found_in_color_dict(checkpoints_1)
2
True
3
>>> found_in_color_dict(checkpoints_2)
4
False
5
>>> found_in_color_dict(checkpoints_3)
6
True
7
>>> found_in_color_dict(checkpoints_4)
8
True
9
>>> found_in_color_dict(checkpoints_5)
10
False
11