Dictionaries
CS 110
1
Reminders and Announcements
Next Week
Review
3
Dictionaries
4
The simplest way to think about a dictionary...
Q: How do you say “one” in Spanish using the eng2sp dictionary?
A: “one” is the key in your dictionary. Use it to get the value out.
5
5
eng2sp
"one"
"uno"
key �(ask dictionary a question)
Get the value that corresponds to the key
Example: Creating a Dictionary
eng2sp = {
"one": "uno",
"two": "dos",
"three": "tres"
}
6
Keys�(left)
Values�(right)
Analogy: Reading data from a list
eng = [
"one",
"two",
"three"
]
print(eng[0])
print(eng[1])
7
OUTPUT:
one
two
Dictionaries are similar: Reading a single value from a dictionary
eng2sp = {
"one": "uno",
"two": "dos",
"three": "tres"
}
val = eng2sp.get("three")
print(val)
print(eng2sp["two"])
8
OUTPUT:
tres
dos
Keys
Example: Iterating through dictionary entries
eng2sp = {
"one": "uno",
"two": "dos",
"three": "tres"
}
for key in eng2sp:
print(key, ":", eng2sp[key])
OUTPUT
one : uno
two : dos
three : tres
9
01_dictionary.py
Dictionaries (Cheat Sheet)
10
Create a dictionary | my_dict = {} |
Get element from a dictionary | my_dict.get(key) |
Add/replace items in dictionary | my_dict[key] = value |
Remove items from dictionary | del my_dict[key] |
Iterate through a dictionary | for key in my_dict:� print(key, my_dict[key]) |
Check if key exists in dictionary | if my_dict.get(key) != None |
Dictionary Applications
Why are dictionaries useful?
11
Dictionaries: How are they useful?
12
Complex Lookup tables and crosswalks
Challenge: Write a program that prompts the user for a state and then prints the capital of that state to the screen. Keep prompting the user until they type "Q" at the prompt.
Recall: this is how you access a value from a dictionary based on a key:�print("The capital of Florida is:", capital_lookup.get("Florida"))
OUTPUT
The capital of Florida is: Tallahassee
13
02_dictionary_lookup_exercise.py