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 :
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