Efficient lookup in list of dictionaries

David Pratt fairwinds at eastlink.ca
Mon Dec 5 04:58:13 CET 2005

Hi. I like working with lists of dictionaries since order is preserved 
in a list when I want order and the dictionaries make it explicit what 
I have got inside them. I find this combination very useful for storing 
constants especially. Generally I find myself either needing to 
retrieve the values of constants in an iterative way (as in my 
contrived example below). Perhaps even more frequent is given one value 
is to look up the matching value in a dict (contained in the list) and 
then obtain the value of another element in the same dictionary.

Most of these lists are generally small so not normally a big deal but 
I have one a list that contains about 100 or more dictionaries with 
several elements and am thinking there is likely a more efficient way 
of doing the lookup.  For example if I have say 5000 insertions to do 
into a database but have to check my constants since they effect what 
is inserted (and it is doing a lookup each time before an insertion is 
made), it is likely adding much to my processing time. At this point I 
do not want store the constants themselves in a database table. I 
usually use the lists by just importing them when needed.

Can someone advise a more efficient lookup when using lists of 
dictionaries. Many thanks.


	{'color':'red', 'shape':'octagon'},
	{'color':'yellow', 'shape':'triangle'},
	{'color':'green', 'shape':'circle'}]

def getShapeForColor(color):
	shape = None
	for test_constant in TEST_CONSTANTS:
		if test_constant['color'] == color:
			shape = test_constant['shape']
	return shape

More information about the Python-list mailing list