[Tutor] Python 3 dictionary questions

Peter Otten __peter__ at web.de
Wed Nov 23 14:32:38 CET 2011


Cranky Frankie 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.

The last one always wins. Perhaps it becomes clearer if you think of

d = {1:1, 1:2}

as syntactic sugar for

d = dict()
d[1] = 1
d[1] = 2

If you want to allow for multiple values per key use a list as the value and 
append to that:

>>> d = {}
>>> for k, v in [(1, 1), (2, 2), (1, 3)]:
...     d.setdefault(k, []).append(v)
...
>>> d
{1: [1, 3], 2: [2]}

> 2) Is there a way to print out the actual value of the key, like
> Montana would be 0, Tarkington would be 1, etc?

No, the actual key *is* "Montana" or "Tarkington". The dictionary does not 
record the insertion order. 
There is a collections.OrderedDict, but I recommend that you don't try out 
that until you have grokked the builtin dict. As a rule of thumb there are 
less usecases for an OrderedDict than you think ;)




More information about the Tutor mailing list