trying to understand dictionaries

Albert Hopkins marduk at letterboxes.org
Fri Jun 12 08:34:57 EDT 2009


On Fri, 2009-06-12 at 04:51 -0700, khemeia at gmail.com wrote:
> Hi.
> As the subject says, I'm a newbie trying to learn python and now
> dictionaries. I can create a dict, understand it and use it for simple
> tasks. But the thing is that I don't really get the point on how to
> use these in real life programing.
> 
> For example I tryed to create a very simple phonebook
> 
> code:
> 
> d = {'fname': [], 'ename': []}
> name1 = 'ricky'
> name2 = 'martin'
> d['fname'].append(name1)
> d['ename'].append(name2)
> 
> name1 = 'britney'
> name2 = 'spears'
> d['fname'].append(name1)
> d['ename'].append(name2)
> 
> 
> This gives me:
> {'ename': ['martin', 'spears'], 'fname': ['ricky', 'britney']}
> 
> I wonder if this is a correct usage and thinking about dictioaries in
> python.
> Everything in my example is based on a serval lists in a dictionary,
> and person 1 is == ename[0] & fname[0]
> and person 2 is == ename[1] & fname[1], it's based on position and
> indexing.
> 
> Is this correct if no, how would you do it?
> if yes, how can I print the result out in a nice way? I need a for-
> loop that prints:
> all [0] in all lists
> all [0] in all lists and so on.

That's probably not the data model I'd use for a phone book.  The
following isn't either, but is better:

d = dict()
d[('martin', 'ricky')] = '555-1212'
d[('spears', 'britney')] = '555-1213'

for last, first in d:
    phone_number = d[(last, first)]
    print ...






More information about the Python-list mailing list