473,799 Members | 2,942 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

dictionary lookup table?

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 dictionary. But it
seems a waste. I end up having to assign an artificial value to the
dictionary entry. Below I assign the value "None" to each dictionary
entry.

Is there a better way? I feel like I'm misusing the dictionary.

#! /usr/bin/env python
import random
import time

dict = {}
list = []

n = 10000
n = 10000
for i in range(n):
str = '%s' % random.random()
list.append(str )
dict[str] = None # <-- seems a waste

sortedList = list[:]
sortedList.sort ()

t1 = time.time()
for i in range(n):
if sortedList[i] not in list:
print 'not found'
print 'List lookups: %.3f sec' % (time.time() - t1)

t1 = time.time()
for i in range(n):
if not dict.has_key(so rtedList[i]):
print 'not found'
print 'List lookups: %.3f sec' % (time.time() - t1)
~
~
~
~
~
:!lookup.py
List lookups: 28.848 sec
List lookups: 0.041 sec

Hit ENTER or type command to continue


Jul 18 '05 #1
2 6585
"John Mudd" <mu**@vex.net > wrote in message
news:ma******** *************** *************@p ython.org...
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 dictionary. But it
seems a waste. I end up having to assign an artificial value to the
dictionary entry. Below I assign the value "None" to each dictionary
entry.

Is there a better way? I feel like I'm misusing the dictionary.
You ARE misusing both dictionaries AND lists, but not in the way you think:
dict = {}
list = []


These lines obliterates the dict() and list() builtins! Use different
names, like D, mydict, etc.

Now, to answer your question:
I don't think you are abusing the dictionary at all, but if you're using
Python 2.3, you can use the set module, which more closely matches the
semantics of your problem. However, as of now the set module is implemented
with dictionaries anyway, so I don't see that you gain much. (I think set
will be implemented as an extension later, though.)

Further, don't be too worried about "waste", because there's very little
waste here. First of all, None is a singleton (hence the Python idiom
"something is None"), so there's no danger of Python possibly making
multiple copies of the item mapped to your key. Secondly, dictionaries are
containers, like lists, so the key and item of a dictionary are just
references to an object. You end up with (at most) twice as many references
in a dictionary as an equivalent list, but references are little more than
dressed-up pointers, and very cheap to store and use. So what are you
worried about?

Finally, if you're worried about waste, why are you using Python? ;) Python
saves your development time in exchange for the far cheaper resource of
memory and processor power.

If you want some more speed (although it looks plenty fast to me), try
experimenting with some other dictionary idioms. Try "if key in
dictionary", "try: D[key]; except: print 'not found'", etc. But I think
you'd be wasting more time than you'd gain, especially since optimization
obsessions can be hard to shake....
--
Francis Avila

Jul 18 '05 #2
In article <vq************ @corp.supernews .com>,
"Francis Avila" <fr***********@ yahoo.com> wrote:
I don't think you are abusing the dictionary at all, but if you're using
Python 2.3, you can use the set module, which more closely matches the
semantics of your problem. However, as of now the set module is implemented
with dictionaries anyway, so I don't see that you gain much.


You gain in expressing more clearly the intent of your code.

--
David Eppstein http://www.ics.uci.edu/~eppstein/
Univ. of California, Irvine, School of Information & Computer Science
Jul 18 '05 #3

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

Similar topics

11
10470
by: Egor Bolonev | last post by:
saluton al ciuj i know how to get item by key ================== dict = {10 : 50, 2 : 12, 4 : 43} print dict >> 12
125
7236
by: Raymond Hettinger | last post by:
I would like to get everyone's thoughts on two new dictionary methods: def count(self, value, qty=1): try: self += qty except KeyError: self = qty def appendlist(self, key, *values): try:
8
5596
by: Rodd Snook | last post by:
I have an application which makes extensive use of the Scripting.Dictionary object. I'm not doing anything silly like putting them outside the page scope -- just creating quite a few of them and stuffing quite a lot of data (from and MS SQL database) into them. On Windows 2000 server, everything is fine. If the data structures get really big it slows down, but for normal operation it's no problem. Recently our hosting provider moved to...
26
4070
by: Alan Silver | last post by:
Hello, I have a server running Windows Server 2003, on which two of the web sites use the MegaBBS ASP forum software. Both sites suddenly developed the same error, which seems to be connected to the dictionary object. After some tinkering, I whittled it down to the following (complete) ASP... <%@ CodePage=65001 Language="VBScript"%>
2
1675
by: John | last post by:
I am trying to design a dictionary in such a way that I can keep the interface and implementation separate. Here is my initial design. Anyone has any comments on it or suggestions on how I could make it better. Does anyone have a good code/pointer that discusses dictionary design. Thanks,
12
3174
by: rudysanford | last post by:
I just started messing with programming and started with Python. Part of my first project deals with translating numerical values to letters. I would like to be able to do the reverse as well, letters to numbers, sort of a table for lookup and a table for reverse lookup. I thought that a dictionary would be the structure to use- write it once and in a second instance swap the keys for values and values for keys. However, reversing a...
3
2523
by: Rich Shepard | last post by:
I need to learn how to process a byte stream from a form reader where each pair of bytes has meaning according to lookup dictionaries, then use the values to build an array of rows inserted into a sqlite3 database table. Here's the context: The OMR card reader sends a stream of 69 bytes over the serial line; the last byte is a carriage return ('\r') indicating the end of record. Three pairs (in specific positions at the beginning of the...
8
3114
by: akameswaran | last post by:
I wrote up a quick little set of tests, I was acutally comparing ways of doing "case" behavior just to get some performance information. Now two of my test cases had almost identical results which was not at all what I expected. Ultimately I realized I don't really know how literals are treated within the interpreter. The two implementations I was looking at were: class caseFunction(object): def __init__(self):
2
3450
by: =?Utf-8?B?c2lwcHl1Y29ubg==?= | last post by:
Hi I have a class that inherits from Generics Dictionary The string that is used for the key is passed thru-out my pgm and sometimes it has modifiers added to the key string that are used in the system. The problem is now I have to strip the modifer to lookup in the Dictionary and I have to copy this code whenever I need to lookup the key or if more modifers are added
0
9538
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10249
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10219
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10025
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7563
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6804
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5584
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4138
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3755
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.