Please type a street number (e.g., 42): 42 Grand Central Terminal is on that street. Please type a street number (e.g., 42): 14 The Con Ed Building is on that street. Please type a street number (e.g., 42): 15 Nothing famous is on that street. Please type a street number (e.g., 42):
If the keys are consecutive
integers,
store the information in a
list.
If the keys are
integers
that are far apart or irregularly spaced,
store the information in a
dictionary.
The output is the same.
dictionary
will usually be
strings,
and we have just seen that the keys could also be
ints.
But the keys cannot be
lists:
#Try to make a dictionary whose keys are lists. buildings = { [5, 34]: "The Empire State Building", [5, 88]: "The Guggenheim", [7, 57]: "Carnegie Hall", [1, 42]: "The United Nations", [7, 32]: "Penn Station" }
Traceback (most recent call last):
File "/Users/myname/python/index.py", line 6, in <module>
[7, 32]: "Penn Station"
TypeError: unhashable type: 'list'
The keys of a
dictionary
must be
immutable,
because we don’t want to have to rearrange the
dictionary
every time someone changes a key.
For example, the keys could be
tuples.
#a dictionary whose keys are tuples buildings = { (5, 34): "The Empire State Building", (5, 88): "The Guggenheim", (7, 57): "Carnegie Hall", (1, 42): "The United Nations", (7, 32): "Penn Station" } while True: try: ave = int(input("Please type an avenue number (e.g., 5): ")) except: #if user did not type a valid int sys.exit(0) try: st = int(input("Please type a street number (e.g., 34): ")) except: #if user did not type a valid int sys.exit(0) try: b = buildings[(ave, st)] #Parentheses are optional. except KeyError: b = "Nothing famous" print(f"{b} is at that corner.") print()
Please type an avenue number (e.g., 5): 5 Please type a street number (e.g., 34): 34 The Empire State Building is at that corner. Please type an avenue number (e.g., 5): 5 Please type a street number (e.g., 34): 35 Nothing famous is at that corner. Please type an avenue number (e.g., 5):