简体   繁体   English

根据另一个(部分)字典过滤字典列表

[英]Filtering List of Dictionaries based on Another (Partial) Dictionary

Suppose I have the following list of dicts and a dict假设我有以下 dicts 列表和一个 dict

dicts = [
    {"lang": "Java", "version": "14", "name": "Java 14"},
    {"lang": "Python", "version": "3.8", "name": "Python 3.8"},
    {"lang": "C++", "version": "17", "name": "C++ 17"},
]
record = {'lang': 'Python', 'version': '3.8'}

How can I find "record" in "dicts", based on "record" having only two of three key value pairs?基于只有三个键值对中的两个的“记录”,如何在“字典”中找到“记录”?

The output would be output 将是

{"lang": "Python", "version": "3.8", "name": "Python 3.8"}
>>> dicts = [
    {"lang": "Java", "version": "14", "name": "Java 14"},
    {"lang": "Python", "version": "3.8", "name": "Python 3.8"},
    {"lang": "C++", "version": "17", "name": "C++ 17"},
]
>>> record = {'lang': 'Python', 'version': '3.8'}
>>> [d for d in dicts if all(d[k] == v for k, v in record.items())]
[{'lang': 'Python', 'version': '3.8', 'name': 'Python 3.8'}]

If you're sure there's only one match (or you only care about getting one and you don't care which), you can make this a call to next with a generator expression:如果您确定只有一个匹配项(或者您只关心获得一个而不关心哪个),您可以使用生成器表达式调用next

>>> next(d for d in dicts if all(d[k] == v for k, v in record.items()))
{'lang': 'Python', 'version': '3.8', 'name': 'Python 3.8'}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM