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

Python – Extract value from list of dictionaries that match a specified key

I have a list of names:

names = ['london','paris']

and I have a list of dictionaries:

data = [
    {   "_id": "ebef3cb1-9053-4d1e-b409-b682236445b7", 
        "name": "london"
    },
    {
        "_id": "0b5d79b5-0d21-4186-b3db-8f4a9f2b25fb",
        "name": "new york",
    },
]

What I want to do is take each element in my names list and match against the value of each "name" key in the data dictionary, and to return the matching values in a list, like this:

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

[london]

I don’t need to worry about duplicates at this stage. It is enough just to take a list of strings to match and see if they appear in my data dictionary. I was looking at a list comprehension but cant figure out the syntax. I was also thinking about making it a boolean check so if either London or Paris match in my dictionary, it returns true.

>Solution :

This can easily be done by looping on both the dictionary and the list, and then comparing the names:

def match_names(names, data):
    ret_list = []
    for name in names:
        for val in data:
            if val['name'] == name:
                ret_list.append(name)
    return ret_list
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