>>> stocks["GOOG"] = (597.63, 610.00, 596.28)
>>> stocks['GOOG']
(597.63, 610.0, 596.28)
Google's price is lower today, so I've updated the tuple value in the dictionary.
We can use this index syntax to set a value for any key, regardless of whether the
key is in the dictionary. If it is in the dictionary, the old value will be replaced
with the new one; otherwise, a new key/value pair will be created.
www.it-ebooks.info
Chapter 6
[
163
]
We've been using strings as dictionary keys, so far, but we aren't limited to string
keys. It is common to use strings as keys, especially when we're storing data in a
dictionary to gather it together (instead of using an object with named properties).
But we can also use tuples, numbers, or even objects we've defined ourselves as
dictionary keys. We can even use different types of keys in a single dictionary:
random_keys = {}
random_keys["astring"] = "somestring"
random_keys[5] = "aninteger"
random_keys[25.2] = "floats work too"
random_keys[("abc", 123)] = "so do tuples"
class AnObject:
def __init__(self, avalue):
self.avalue = avalue
my_object = AnObject(14)
random_keys[my_object] = "We can even store objects"
my_object.avalue = 12
try:
random_keys[[1,2,3]] = "we can't store lists though"
except:
print("unable to store list\n")
for key, value in random_keys.items():
print("{} has value {}".format(key, value))
This code shows several different types of keys we can supply to a dictionary. It also
shows one type of object that cannot be used. We've already used lists extensively,
and we'll be seeing many more details of them in the next section. Because lists can
change at any time (by adding or removing items, for example), they cannot hash to
a specific value.
Objects that are
hashable
basically have a defined algorithm that converts the object
into a unique integer value for rapid lookup. This hash is what is actually used to
look up values in a dictionary. For example, strings map to integers based on the
characters in the string, while tuples combine hashes of the items inside the tuple.
Any two objects that are somehow considered equal (like strings with the same
characters or tuples with the same values) should have the same hash value, and the
hash value for an object should never ever change. Lists, however, can have their
contents changed, which would change their hash value (two lists should only be
equal if their contents are the same). Because of this, they can't be used as dictionary
keys. For the same reason, dictionaries cannot be used as keys into other dictionaries.
www.it-ebooks.info
Python Data Structures
Do'stlaringiz bilan baham: |