tags:

views:

83

answers:

1

I have two list like this:

list1 = [{'id':1, 'name':'foo', 'age':20}, {'id':2, 'name':'foo', 'age':20}]

list2 = [{'id':2, 'created':'2004-12-23'}, {'id':12, 'created':'2004-12-23'}, 
         {'id':1, 'created':'2004-12-23'}]

list1 = [{'id':1, 'name':'foo', 'age':20, 'match':True}, 
         {'id':2, 'name':'foo', 'age':20, 'match':True}]

I want to add match to the corresponding list if the id of list1 and list2 matches. How would I do that efficiently?

+5  A: 
set2 = set(x['id'] for x in list2)
for entry in list1:
  if entry['id'] in set2:
    entry['match'] = True

OR

set2 = set(x['id'] for x in list2)
for entry in list1:
  entry['match'] = entry['id'] in set2
Ignacio Vazquez-Abrams