On Wed, Nov 23, 2011 at 7:04 AM, Cranky Frankie <cranky.fran...@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.mont...@gmail.com","Candlestick Park"],
> "Tarkington": ["Fran", "651-321-7657", "frank.tarking...@gmail.com",
> "Metropolitan Stadidum"],
> "Namath": ["Joe", "212-222-7777", "joe.nam...@gmail.com", "Shea Stadium"],
> "Elway": ["John", "303-9876-333", "john.el...@gmai.com", "Mile High
> Stadium"],
> "Elway": ["Ed", "303-9876-333", "john.el...@gmai.com", "Mile High
> Stadium"],
> "Manning": ["Archie","504-888-1234", "archie.mann...@gmail.com",
> "Louisiana Superdome"],
> "Staubach": ["Roger","214-765-8989", "roger.staub...@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
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to