[Tutor] comparing lists of dictionaries

Kent Johnson kent37 at tds.net
Tue Mar 10 01:23:15 CET 2009

On Mon, Mar 9, 2009 at 5:56 PM, ski <norman at khine.net> wrote:
> i was looking to list all the items in list1 that are not in list2 based on
> the key['id] and key['affiliation'] respectively.

OK. Generally, when you want to test for membership, a set or dict is
a good choice. In this case, I would first make a set of the keys from

In [6]: list2 = [{'affiliation': 'ABTA', 'affiliation_no': u'G3903'},
{'affiliation': 'AAC', 'affiliation_no': u'none'}]

In [8]: list2keys = set(item['affiliation'] for item in list2)

In [9]: list2keys
Out[9]: set(['AAC', 'ABTA'])

Now you can filter list1 items by whether their id is in list2keys:

In [10]: list1 = [{'is_selected': False, 'id': 'AAC', 'title':
'Association of Airline Cons.'}, {'is_selected': False, 'id': 'AALA',
'title': 'Adv. Activity Licence. Auth.'}, {'is_selected': False, 'id':
'ABPCO', 'title': 'Association of British Prof. Conf. Organisation'},
{'is_selected': True, 'id': 'ABTA', 'title': 'Association of British
Travel Agents'}, {'is_selected': False, 'id': 'ABTOT', 'title':
'Association of Bonded Travel Organisation Trust'}, {'is_selected':
False, 'id': 'AERA', 'title': 'Association of Europe Rail Agents'}]

In [11]: for item in list1:
   ....:     if item['id'] not in list2keys:
   ....:         print item

{'title': 'Adv. Activity Licence. Auth.', 'id': 'AALA', 'is_selected': False}
{'title': 'Association of British Prof. Conf. Organisation', 'id':
'ABPCO', 'is_selected': False}
{'title': 'Association of Bonded Travel Organisation Trust', 'id':
'ABTOT', 'is_selected': False}
{'title': 'Association of Europe Rail Agents', 'id': 'AERA',
'is_selected': False}


More information about the Tutor mailing list