[Tutor] Python 3 dictionary questions

Wayne Werner waynejwerner at gmail.com
Wed Nov 23 14:30:25 CET 2011


On Wed, Nov 23, 2011 at 7:04 AM, Cranky Frankie <cranky.frankie at gmail.com>wrote:

> In playing around with Pyton 3 dictionaries I've come up with 2 questions
>
> 1) How are duplicate keys handled? For example:
>
> Qb_Dict = {"Montana": ["Joe", "Montana", "415-123-4567",
> "joe.montana at gmail.com","Candlestick Park"],
> "Tarkington": ["Fran", "651-321-7657", "frank.tarkington at gmail.com",
> "Metropolitan Stadidum"],
> "Namath": ["Joe", "212-222-7777", "joe.namath at gmail.com", "Shea Stadium"],
> "Elway": ["John", "303-9876-333", "john.elway at gmai.com", "Mile High
> Stadium"],
> "Elway": ["Ed", "303-9876-333", "john.elway at gmai.com", "Mile High
> Stadium"],
> "Manning": ["Archie","504-888-1234", "archie.manning at gmail.com",
> "Louisiana Superdome"],
> "Staubach": ["Roger","214-765-8989", "roger.staubach at gmail.com",
> "Cowboy Stadium"]}
>
> print(Qb_Dict["Elway"],"\n")                        # print a dictionary
> entry
>
> In the above the "wrong" Elway entry, the second one, where the first
> name is Ed, is getting printed. I just added that second Elway row to
> see how it would handle duplicates and the results are interesting, to
> say the least.
>
> 2) Is there a way to print out the actual value of the key, like
> Montana would be 0, Tarkington would be 1, etc?


I'm not sure about #1, but I can tell you about #2.

Dictionaries are not ordered, so you have absolutely no guarantee which
order they'll appear in when you print them out, or if you iterate over the
dictionary. If you want to maintain some type of order you have a few
options. First, store the keys in a list, which does maintain order:

keys = ['Elway', 'Montana', ... ]

Then you would do something like:

Qb_Dict[keys[0]]

(As a slight aside, I'll direct you to PEP 8 which is the Python style
guide which contains things like naming conventions. If you want your code
to look Pythonic, you should take a look there.)

If you just want them to be sorted, you can run sorted on the keys()
collection from the dictionary:

for key in sorted(Qb_Dict.keys()):
    print(Qb_Dict[key])

In Python 3 this will only work if your collection contains comparable
types - if you have {1:'Hello', 'Goodbye':2} then you'll get a TypeError
when it tries to compare 1 and 'Goodbye'

HTH,
Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20111123/0ccbde86/attachment.html>


More information about the Tutor mailing list