Filtering List of Dictionaries based on Another (Partial) Dictionary

Advertisements

Suppose I have the following list of dicts and a 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

{"lang": "Python", "version": "3.8", "name": "Python 3.8"}

>Solution :

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

Leave a ReplyCancel reply