Which is fastest dict or list.index() ?

Gustavo Cordova gcordova at hebmex.com
Mon Jun 3 16:48:46 EDT 2002


> 
> I need a structure to hold a correspondence between toons and id like
> 
> {'Bugs' : 0, 'Mickey' : 1, 'Babs' : 2, 'Jerry' : 3, 'Tom' : 
> 4, 'Babs' : 5}
> 
> I must be able to alpha sort these toons (without loosing 
> their id), and access a toon from an id or an id from a toon.
> 
> By now a use a dict and a list : the dict gives index from a 
> toon, and the list gives me a toon from an index.
> 
> {'Bugs' : 0, 'Mickey' : 1, 'Babs' : 2, 'Jerry' : 3,
   'Tom : 4, 'Babs' : 5}
> ['Bugs', 'Mickey', 'Babs', 'Jerry', 'Tom', 'Babs']
> 
> (the id is used somewhere else a key to a collection of elements)
> 
> My question is which is the best way (best = quickest and 
> memory safe) to handle this ?
> Should i subclasse from dict or list ?
> Should i consider using only one list with toons (and use 
> their index as id)
> ?
> Should i use 2 dicts ?
> 
> Many thanks to you for helping
> 
> s13.
> 

Hmmm... OK, first, let's analyze your data domain:

"Toon names", which are character strings;
"Toon Name Indexes", which are integer numbers.

That gives us an insight: You'll never have a clash
between a "ToonName" and a "ToonNameIndex".

In such a case (I've used this technique before,
with good results). I'd really recommend you use
a single object, a dictionary, subclassed if you
like, to store all the information.

So, you can say "toondict[5]" and obtain "Babs",
and say "toondict['Babs']" and obtain 5.

Since, now, keys and values are transposed, you need
special methods to obtain all toons and indexes,
so it's trivial to separate all contained data
to find what you need.

This will give you the piece of mind (hah!) that
you're not duplicating functionality.

I'd subclass 'dict' like this:

class ToonDict(dict):
  # All stays the same, except:
  def __setitem__(self, key, value):
    # Special-case item insertion.
    dict.__setitem__(self, key, value)
    dict.__setitem__(self, value, key)

  # Obtain list of data of a certain type.
  def __typed_data(self, *types):
    items = self.values()
    items = filter(lambda i:type(i) in types, items)
    items.sort()
    return items

  # Retrieve a sorted list of toon names.
  def toons(self): return self.__typed_data(str)

  # Retrieve a sorted list of toon name indexes.
  def toon_name_indexes(self): return self.__typed_data(int)


Good luck :-)

-gus





More information about the Python-list mailing list