is this use of lists normal?

Jeff Shannon jeff at ccvcorp.com
Mon Jan 24 20:55:58 EST 2005


Gabriel B. wrote:

> My object model ended up as
> 
> DataStorageObj
> |-itemsIndex (list, could very well be a set...)
> |  |-[0] = 0
> |  |-[1] = 1
> |  |-[2] = 5
> |  '-[3] = 6
> '-Items (list)
>    |-[0] = ['cat food', '12,20']
>    |-[1] = ['dog food', 8,00']
>    |-[2] = ['dead parrot', '25,00']
>    '-[3] = ['friendly white bunny', '12,25']
> 
> the list itemsindex has the DB index of the data, and the list items
> has the data.
> So if i want something like "SELECT * FROM items WHERE idx=5" i'd use
> in my program
> self.items[ self.itemsIndex.index(5) ] 
> i reccon that's not much nice to use when you're gona do /inserts/ but
> my program will just read the entire data and never change it.
> 
> Was i better with dictionaries? the tutorial didn't gave me a good
> impression on them for custom data...
> Tupples? the tutorial mentions one of it's uses 'employee records from
> a database' but unfortunatly don't go for it...

Yes, I think you'd be better off using dictionaries here.  You can 
spare yourself a level of indirection.

Tuples would be a good way to store the individual items -- instead of 
a list containing a name and a price (or so I presume), you'd use a 
tuple.  Your data storage would then be a dictionary of tuples --

self.items = { 0: ('cat food', '12,20'),
                1: ('dog food', '8,00'),
                5: ('dead parrot', '25,00'),
                6: ('friendly white bunny', '12,25') }

Then your SELECT above would translate to

     my_item = self.items[5]

and my_item would then contain the tuple ('dead parrot', '25,00').

Note that the most important difference between tuples and lists, for 
this example, is conceptual.  Tuples generally express "this is a 
collection of different things that are a conceptual group", whereas 
lists express "this is a series of similar objects".


> i think the 'ideal' data model should be something like
> ({'id': 0, 'desc': 'dog food', 'price': '12,20'}, ...)
> But i have no idea how i'd find some item by the ID within it withouy
> using some loops

You could use a dictionary for each item, as you show, and then store 
all of those in a master dictionary keyed by id -- in other words, 
simply replace the tuples in my previous example with a dict like what 
you've got here.  You could also create a simple class to hold each 
item, rather than using small dicts.  (You'd probably still want to 
store class instances in a master dict keyed by id.)

Generally, any time your problem is to use one piece of information to 
retrieve another piece (or set) of information, dictionaries are very 
likely to be the best approach.

Jeff Shannon
Technician/Programmer
Credit International





More information about the Python-list mailing list