Reputation: 1052
I am having two dicts, one in list:
var_a = [{'name':"John",'number':21},{'name':"Kevin",'number':23}]
var_b = {'21':"yes"},{'24':"yes"}
I need to compare var_a and var_b with the key from var_b with the number value in var_a.
I have tried this and got the output:
for key, value in var_b.iteritems():
for l in var_a:
if l['number'] == key:
print l
This needs two loops to get the output. So is there any way to finish this is single loop with python 2.7?
Upvotes: 0
Views: 63
Reputation: 219
I think you need to use the lambda function with one for-loop:
for key, value in var_b.iteritems():
result = filter(lambda d: d['id'] == key, var_a)
The result will give you the output for sure.
Upvotes: 0
Reputation: 4472
You can use map
to create a keys set from var_b
keys and then loop only over var_a
to check if the number value exists in the var_b
keys set
var_a = [{'name':"John",'number':21},{'name':"Kevin",'number':23}]
var_b = [{'21':"yes"},{'23':"no"}]
keys_set = set(map(lambda x: int(list(x.keys())[0]), var_b))
for i in var_a:
if i['number'] in keys_set:
print(i)
Output
{'name': 'John', 'number': 21}
{'name': 'Kevin', 'number': 23}
Upvotes: 1