Efficient lookup in list of dictionaries

David Pratt fairwinds at eastlink.ca
Mon Dec 5 05:55:03 EST 2005


This is a lot less clumsy and can easily be used in a class which is 
very nice!
Many thanks bruno and Rob E for this good advice.

Regards,
David

On Monday, December 5, 2005, at 05:31 AM, bruno at modulix wrote:

> David Pratt wrote:
> (snip)
>> Can someone advise a more efficient lookup when using lists of
>> dictionaries. Many thanks.
>>
>>
>> TEST_CONSTANTS = [
>>     {'color':'red', 'shape':'octagon'},
>>     {'color':'yellow', 'shape':'triangle'},
>>     {'color':'green', 'shape':'circle'}]
>
> COLOR_INDEX = dict([(item['color'], item) for item in TEST_CONSTANT])
> SHAPE_INDEX = dict([item['shape'], item) for item in TEST_CONSTANT])
>
> def getShapeForColor(color):
>   return COLOR_INDEX.get(color, {'shape':None})['shape']
>
> def getColorForShape(shape):
>   return SHAPE_INDEX.get(color, {'color': None})['color']
>
> This of course assume that there are no duplicate colors nor shapes.
>
> -- 
> bruno desthuilliers
> python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) 
> for
> p in 'onurb at xiludom.gro'.split('@')])"
> -- 
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list