Efficient lookup in list of dictionaries

Rob E remm1 at member.fsf.org
Sun Dec 4 23:18:54 EST 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.

Instead of doing this in an iterative way -- create a dictionary that
points to the correct dictionary, i.e., who's key is the search key and
whose value is the dictionary (or list of dicts if more than one).  This
approach is basically accelerating the lookup by creating a special index.

Another way of doing this is to create a class that works like an
"ordered" dictionary.  Once can do this with a little programming -- for
example by putting your data in a list and creating a dict that indexes 
the records of the list -- i.e. the key is the index and the value is the
index of the list.  This is pretty much how databases work.

Rob





More information about the Python-list mailing list