[Tutor] class Clowning: saving references to other instances

Jeff Shannon jeff@ccvcorp.com
Tue, 18 Dec 2001 09:34:22 -0800


> Rob McGee <i812@iname.com> wrote:
>
> I will try a dictionary instead of a
> list. Did you see my post about "dictionary vs. list considerations"
> after this one? I was thinking that dictionaries would take up a lot
> more memory. The one response I got indicated that speed of execution
> would probably be better with dictionaries. But I was afraid that they
> might hog a lot more memory?

Dictionaries do use a bit more memory than lists, but really, it's unlikely that
you have any reason to worry about it unless you are working with embedded
devices or some such.  On a modern (within ~5 years old) PC, you'd need to be
using *thousands* of dictionaries (or a few dictionaries with many thousands of
entries) before you'd be likely to be affected by memory constraints.  (How many
200-300 byte structures can fit in 64MB of RAM? ;) )

The better way to decide between lists and dictionaries, is to look at which fits
your problem domain better--which one makes things clearer and easier to read?
If you're accessing the data in a regular, ordered sequence, or it will be
convenient to look them up by a numeric index, then use a list.  If you want to
use some other method of looking up data, such as finding it by "name", then use
a dictionary.  In 99% of the circumstances you're likely to work in, the
performance difference will be negligible.


> ISTM if I switch to dictionaries I could use the objects themselves as
> the keys? But I don't (yet) see how that would be easier than strings as
> keys. The input will originate from the user, which of course means it
> starts out as a string. I'll have to think about it some more.

You *could* use the objects themselves as keys--*if* they are hashable.  This
means that they'd have to never mutate once they were in the dict, and  you'd
probably have to give them a __hash__() function.  It's probably a lot easier to
stick with using the strings.  :)


Jeff Shannon
Technician/Programmer
Credit International