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
int
egers,
store the information in a
list
.
If the keys are
int
egers
that are far apart or irregularly spaced,
store the information in a
dict
ionary.
The output is the same.
dict
ionary
will usually be
str
ings,
and we have just seen that the keys could also be
int
s.
But the keys cannot be
list
s:
#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
dict
ionary
must be
immutable,
because we don’t want to have to rearrange the
dict
ionary
every time someone changes a key.
For example, the keys could be
tuple
s.
#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):