[Tutor] Dictionary Keys
Danny Yoo
dyoo@hkn.eecs.berkeley.edu
Tue, 6 Aug 2002 14:24:13 -0700 (PDT)
On Tue, 6 Aug 2002, Jeff Shannon wrote:
> Alan Colburn wrote:
>
> > Basically, what do y'all tend to do when you are entering/saving
> > information in a dictionary and, the way you've set up your script's
> > parameters, you could conceivably create key:value combinations with
> > identical keys (but different values)?
As another example, we can use a language dictionary. A word may have
several definitions based on context. For example, the simple-looking
word "set" is both a noun and a verb, and, even as a noun, it has multiple
definitions based on context.
"I am trying to complete my set of Pokemon trading cards."
"The set of prime numbers, excluding two, consists of odd numbers."
"Set that turkey aside, near the pumpkin."
> > for the sake of concreteness, suppose a medical office is recording
> > patient visits (patient's name, visit date, other information), using
> > the patient's name as the key. The rest of the information is the
> > key's value, perhaps stored in a list. If each visit represents a
> > separate key:value combination, and a person makes multiple visits to
> > the office, then ...?
>
> Well, to a large degree it depends on the specific application, but a
> common idiom is to use a list of values if there is more than one
> value for a given key. Something like
>
> KeyA : ValueA
> KeyB : [ValueB1, ValueB2, ValueB3]
> KeyC : ValueC
To make the code cleaner, we often force the situation that the values are
always lists, even lists of length one:
###
KeyA: [ValueA]
KeyB: [ValueB1, ValueB2, ValueB3]
KeyC: [ValueC]
###
Although this seems a little wasteful, it turns out that it lets us avoid
writing a special case that handles the storage of just one value. We can
say that our dictionary maps patient names to their "visit history", and
assume that the visit history is always a list of their visits.
Talk to you later!