我的示例数据:
list_of_dict =[{'cena': 23, 'nazwa': 'item1', 'param': 'pampam'},
{'cena': 26, 'nazwa': 'item2', 'param': 'iko' },
{'cena': 26, 'nazwa': 'item2a','param': 'ik2' },
{'cena': 26, 'nazwa': 'item2b','param': 'ik2' },
{'cena': 17, 'nazwa': 'item3', 'param': 'etr' },
{'cena': 17, 'nazwa': 'item4', 'param': 'asdf' }]
conditions = {'cena': 26, 'param': 'ik2' }
我尝试过:
if conditions in list_of_dict:
do_something()
它可以工作,但只有当整个条件字典(每个键)与字典列表中的一个匹配时才能运行,我的意思是:
In [1]: exampleSet = [{ 'type' : 'type1', 'k' : 'kval'},
...: { 'type' : 'type2', 'k' : 'kv2' },
...: { 'type' : 'type2', 'k' : 'k3' },
...: { 'type' : 'type3', 'k' : 'k3' }]
...:
...: conditions = { 'type' : 'type1', 'k' : 'kval' }
...:
...:
...: conditions in exampleSet
...:
Out[1]: True
In [2]: conditions = { 'type' : 'type1' }
In [3]: conditions in exampleSet
Out[3]: False
当我尝试将键值对指定的字典进行匹配时(无论值/未指定值是否存在),所以
In [4]: exampleSet = [{ 'type' : 'type1', 'k' : 'kval'},
...: { 'type' : 'type2', 'k' : 'kv2' },
...: { 'type' : 'type2', 'k' : 'k3' },
...: { 'type' : 'type3', 'k' : 'k3' }]
...:
...: conditions = { 'type' : 'type2' }
...:
...: my_wanted_match( exampleSet, conditions )
必须返回:
[{ 'type' : 'type2', 'k' : 'kv2' },
{ 'type' : 'type2', 'k' : 'k3' }]
作为结果。
有人可以给我一些关于如何实现这个目标的提示吗?