[Tutor] Dictionary Question.

Magnus Lycka magnus@thinkware.se
Fri, 06 Sep 2002 12:07:08 +0200


At 14:15 2002-09-05 -0700, S A wrote:
>Let me first setup the scenario:
>
>I have a dictionary that contains keys that are names of people. Each one 
>of these keys contains three items:
>1.phone number
>2.address
>3.email

My mail at http://mail.python.org/pipermail/tutor/2002-August/016173.html
relates to this. Sorry for the MIME garbage in the text. (Can't someone
fix the mail archive to encode MIME?) Replace =3D with = and =20 with space
and it shold be fairly understandable.

>The program is set up to first ask the user to input a new key(name). Then 
>the user is asked to enter first the phone number, followed by the 
>address, and finally the email. This of course is repeated for many 
>keys(names). (kinda of like an addressbook)
>
>I want to ensure first that each item for the key is listed in the same 
>order of input:
>
>{key:('phone number', 'address', 'email')}

Do you mean that phone number comes first, address next and email last?
Sure, if you put those in a tuple as you suggest here, it's given. Like
this:

...
name = raw_input('Name: ')
phone = raw_input('Phone: ')
address = raw_input('Address: ')
email = raw_input('Email: ')
dictionary[name] = (phone, address, email)
...

Another option is to use a list instead of a tuple:

...
name = raw_input('Name: ')
dictionary[name] = raw_input('Phone: ')
dictionary[name].append(raw_input('Address: '))
dictionary[name].append(raw_input('Email: '))
...

But I would use the first version with the tuples.

>Will this be the case for every key? Or will the list for every key place 
>the values in random order?
>
>Next is there a way to sort the keys, say alphabetically, without 
>disturbing the key:value relationship? (In case you have not yet noticed, 
>I'm trying to build a simple database using dictionaries and I need to be 
>able to enter/retrieve fields for specific relational keys)

A dictionary is never sorted. You can have no influence
over this without fixing the hash-values for your keys,
and that might be little to close to magic for this list.

You can extract your keys to a list, and sort that list,
and finally use the sorted list to extract your data:

dict = <your dictionary with name keying a tuple as above>

format = "Name: %s, Phone: %s, Address: %s, Email: %s"

keys = dict.keys()
keys.sort()

for name in keys:
     print format % (name,) + dict[name]

But if you just loop over the dictionary items as below,
you can't influence the order.

for entry in dict.items():
     ...

That would be against the nature of a dictionary...


-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se