【发布时间】:2016-07-31 03:29:33
【问题描述】:
我的示例数据:
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()
它有效,但只有当整个条件 dict(每个键)与 dict 列表中的一个匹配时,我的意思是:
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' }]
结果。
谁能给我一些关于如何实现这一点的提示?
【问题讨论】:
-
我曾经回答过一个基本上可以归结为完全相同的问题的问题,如果我理解正确的话:emulating the behavior of findWhere() in python
标签: python list dictionary filter matching