'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:
[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 1:[1]
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
Solution 2:[2]
How about
def match_names(names: list|set, data:List[dict]) -> List[str]:
return [d["name"] for d in data if d["name"] in names]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Khalil |
Solution 2 | Anders Steen Nilsen |