Pythonic search of list of dictionaries

Scott David Daniels Scott.Daniels at Acm.Org
Tue Jan 4 14:03:17 EST 2005


Skip Montanaro wrote:
> ...lotsa great stuff ...
> You might want to sort your lists by the 'English' key.  I don't know how to
> use the new key arg to list.sort(), but you can still do it the
> old-fashioned way:
> 
>     oldl.sort(lambda a,b: cmp(a['English'], b['English']))
>     newl.sort(lambda a,b: cmp(a['English'], b['English']))

To complete the thought, for 2.4 and after the new-fashioned way is:

     import operator

     oldl.sort(key=operator.itemgetter('English'))
     newl.sort(key=operator.itemgetter('English'))

> Once sorted, you can then march through the lists in parallel, which should
> give you an O(n) algorithm.  
But overall you will have O(n log n) because of the sorts.

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list