Efficient lookup in list of dictionaries

bruno at modulix onurb at xiludom.gro
Mon Dec 5 04:31:06 EST 2005


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('@')])"



More information about the Python-list mailing list