Reputation: 6139
I have a dictionary inside a list :
list1 = [{'Value': 'John','Key': 'Name'},{'Value':'17','Key': 'Number'}]
And i have a list:
list2 = ['Name','Number']
How to check the values inside list2 are present in the list1. If present i need to list the the Value.
Eg: If Name is present , print "John"
Upvotes: 0
Views: 42
Reputation: 6526
Here is my one-line style suggestions easily readable IMHO.
First solution with result sorted in the same order as list1
:
list1 = [{'Value': 'John','Key': 'Name'},{'Value':'17','Key': 'Number'}]
list2 = ['Name','Number']
values = [x['Value'] for x in list1 if x['Key'] in list2]
print(values)
# ['John', '17']
Second solution with result sorted in the same order as list2
:
list1 = [{'Value': 'John','Key': 'Name'}, {'Value':'17','Key': 'Number'}]
list2 = ['Number', 'Name']
values = [x['Value'] for v in list2 for x in list1 if x['Key'] == v]
print(values)
# ['17', 'John']
Upvotes: 1
Reputation: 164843
You can use a for
loop. Note I use set
for list2
to enable O(1) lookup within your loop.
list1 = [{'Value': 'John','Key': 'Name'},{'Value':'17','Key': 'Number'}]
list2 = {'Name', 'Number'}
for item in list1:
if item['Key'] in list2:
print(item['Value'])
# John
# 17
Upvotes: 1
Reputation: 27331
First of all I would transform your list1
into its destiny: a dictionary.
dict1 = {d['Key']: d['Value'] for d in list1}
Then you can simply loop over list2
and print the value if the key is there:
for key in list2:
if key in dict1:
print(dict1[key])
This prints:
John
17
Upvotes: 0
Reputation: 5424
Please also read the comments:
for i in list2: #iterate through list2
for j in list1: #iterate through list of dictinaries
if i in j.values(): #if value of list2 present in the values of a dict then proceed
print(j['Value'])
Upvotes: 1