trying to understand dictionaries

Jean-Michel Pichavant jeanmichel at
Fri Jun 12 08:25:37 EDT 2009

Basically, dictionaries are a bunch of couples of key and  value where 
key is an immutable object. In fact you'll find a more accurate 
definition in any python book or online tutorial.
The thing is that keys are usually used as an easy and quick way the 
search and index items.
You can see dict as a list that can use strings instead of integers to 
index its values.

phonebook = {
    'ricky' : ('ricky', 'martin', 'male'),
    'britney' : ('britney', 'spears', 'female'),
    'myBestBuddy' : ('barack', 'obama', 'male'),
    42 : ('bob', 'bib', 'male'), # you can use 42 as index, like strings 
integers are not mutable
    True: ('', '', ''), # meaningless example just to show that any 
immutable object will fit as index

fname, ename, gender = phonebook['myBestBuddy']
fname, ename, gender = phonebook[42]

Keys are unique among the dictionary.


khemeia at 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.
> thanks
> /jonas

More information about the Python-list mailing list