Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filtering List of Dictionaries based on Another (Partial) Dictionary

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{"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'}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading