Dictionary Literal Values
A dict literal is created by surrounding a
key-value list with {}'s; a keys is
separated from its value with :'s, and the
key
:
value
pairs are separated with commas (,). An empty
dict is simply {}. As with
lists and tuples, an extra
, inside the {}'s is tolerated.
Examples:
diceRoll = { (1,1): "snake eyes", (6,6): "box cars" }
myBoat = { "NAME":"KaDiMa", "LOA":18,
"SAILS":["main","jib","spinnaker"] }
theBets = { }
The diceRoll variable is a
dict with two elements. One element has a key of
a tuple (1,1) and a value of a
string, "snake eyes". The
other element has a key of a tuple
(6,6) and a value of a string
"box cars".
The myBoat variable is a
dict with three elements. One element has a key
of the string "NAME" and a
value of the string "KaDiMa".
Another element has a key of the string
"LOA" and a value of the integer
18. The third element has a key of the
string "SAILS" and the value
of a list ["main", "jib",
"spinnaker"].
The theBets is an empty
dict.
The values and keys in a dict do not have
to be the same type. Keys must be a type that can produce a hash value.
Since lists and dict
objects are mutable, they are not permitted as keys. All other
non-mutable types (especially strings,
frozensets and tuples) are
legal keys.