[Tutor] Python 3 dictionary questions

Christian Witts cwitts at compuscan.co.za
Wed Nov 23 14:27:42 CET 2011


On 2011/11/23 03:04 PM, 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.
>
> 2) Is there a way to print out the actual value of the key, like
> Montana would be 0, Tarkington would be 1, etc?
>
A dictionary is simply a Key:Value store and keys are unique.  You're 
overwriting your first "Elway" entry with the second one when it's being 
"captured". If you want to keep duplicate "key" values you'll need to 
re-look at what data structure you want to use, you can keep using a 
dictionary but then you'll need to change the value side of it perhaps 
like `{key: {key: value, key: value}}` so you end up with `{'Elway': 
{'John': [tel_num, email, home_ground], 'Ed': [tel_num, email, 
home_ground]}}` or some other implementation specific to your requirements.

As for your second question, the value of the key is a hash. So to get 
the value, you'll need to find what hashing algorithm is used by default 
for dictionaries and use that to get the value of it yourself.

-- 

Christian Witts
Python Developer
//
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20111123/33805856/attachment.html>


More information about the Tutor mailing list