[Tutor] Multiple identical keys in a dictionary

Daniel Yoo dyoo@hkn.eecs.berkeley.edu
Sat, 26 May 2001 09:51:23 -0700 (PDT)


On Sun, 27 May 2001, wheelege wrote:

>   Anyway, the essence of the problem is...
> 
> >>> d = {100: ['Jim', 'Hard', 10], 50: ['Bob', 'Easy', 6], 20: ['Fred', 'Silly', 2]}
> >>> d[50] = ['Darren', 'Medium', 3]
> >>> d
> {100: ['Jim', 'Hard', 10], 20: ['Fred', 'Silly', 2], 50: ['Darren', 'Medium', 3]}
> 
>   And I'm probably asking for the impossible, but what I'd like instead is...
> 
> >>> d = {100: ['Jim', 'Hard', 10], 50: ['Bob', 'Easy', 6], 20: ['Fred', 'Silly', 2]}
> >>> d[50] = ['Darren', 'Medium', 3]
> >>> d
> {100: ['Jim', 'Hard', 10], 20: ['Fred', 'Silly', 2], 
>  50: ['Darren', 'Medium', 3], 50: ['Bob', 'Easy', 6]}

One way you can do this is by having the dictionary go from a particular
score to list of people who've gotten that score.  Let's take a look at
how the structure might initially look like.

    d = {100: [['Jim', 'Hard', 10]], 
         50: [['Bob', 'Easy', 6]],
         20: [['Fred', 'Silly', 2]]}

This will seem weird at first; we'll be containing a lot of lists with
only one element, so it seems wasteful.  However, this approach will allow
us to do to something like this:

    d[50].append(['Darren', 'Medium', 3])

and now we know that a score of 50 matches up with a list of two people.

Good luck to you!