python通过包含几个键值对作为条件的dict过滤dict列表

标签 python list dictionary filter matching

我的示例数据:

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'  }]

结果。

谁能给我一些关于如何实现这一目标的提示?

最佳答案

这是你想要的 filter() - 你想根据某些条件过滤你的字典列表;仅返回符合所有条件的条目。

>>> 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 = {'param':'iko'}

然后做一个单行过滤器:

>>> filter(lambda item: all((item[k]==v for (k,v) in conditions.iteritems())), list_of_dict)
[{'cena': 26, 'param': 'iko', 'nazwa': 'item2'}]

关于python通过包含几个键值对作为条件的dict过滤dict列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36523797/

相关文章:

Python:列表匹配

swift - XCode9.4.1 swift : Showing image instead of text on map annotations

Python将字符串对象转换为字典

python - 值错误 : Feature not in features dictionary

python - 如何导入Excel选项卡并在Python中相应地在新列中给出选项卡的名称?

python - Django 看不到静态文件

python - 为什么 PyCharm 显示无效的 unicode 字符?

java - 从 Android : Java or Python (SL4A) 开始

Python - Gtk.TreeView 和 Gtk.ListStore 获取选定的索引

python - 如何返回字符串中所有大写字母索引的列表?