473,385 Members | 1,521 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Efficient lookup in list of dictionaries

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.

Regards
David

TEST_CONSTANTS = [
{'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
Dec 5 '05 #1
2 2606
> 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
Dec 5 '05 #2
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 'o****@xiludom.gro'.split('@')])"
Dec 5 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Narendra C. Tulpule | last post by:
Hi, if you know the Python internals, here is a newbie question for you. If I have a list with 100 elements, each element being a long string, is it more efficient to maintain it as a dictionary...
2
by: John Mudd | last post by:
I must be missing something here. It's clearly faster to lookup an item directly in a dictionary than to scan through a list. So when I have a large lookup table I always load it in the form of a...
6
by: Neal D. Becker | last post by:
I need a fairly small lookup table, and I'm wondering which data python data structure would be fastest. I could use a list, tuple, dictionary, numeric array, or maybe plain python array. The...
6
by: JezB | last post by:
What is the most efficient way to scan an array for a match ? I could just iterate directly through it comparing each array entry with what I am looking for, I could use an enumerator to do the...
4
by: Andrea Griffini | last post by:
Hello, I implemented that crazy idea and seems working... in its current hacked state can still pass the test suite (exluding the tests that don't like self generated output on stdout from...
13
by: gonzlobo | last post by:
Greetings, and happyNewYear to all. I picked up Python a few weeks ago, and have been able to parse large files and process data pretty easily, but I believe my code isn't too efficient. I'm...
6
by: pj | last post by:
Hi, I 'm currently writing a program that performs transliteration (i.e., converts greek text written using the english alphabet to "pure" greek text using the greek alphabet) as part of my...
9
by: igor.tatarinov | last post by:
Hi, I am pretty new to Python and trying to use it for a relatively simple problem of loading a 5 million line text file and converting it into a few binary files. The text file has a fixed format...
3
by: Ken Fine | last post by:
This is a question that someone familiar with ASP.NET and ADO.NET DataSets and DataTables should be able to answer fairly easily. The basic question is how I can efficiently match data from one...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.