How do we use physical dictionaries?
Image credit: https://www.flickr.com/photos/crdot/5510506796
cs_dept_phonebook = {
"Porter" : "3041",
"Case" : "4618",
"Klinge" : "4599",
"Manley" : "2177",
"Urness" : "2188",
"Rieck" : "3795"
}
cs_dept_phonebook["Manley"]
Each item in a dictionary is a key-value pair
Use a key to look up a value
"Manley" is a key
"2177" is a value
Uses curly braces { }, keys and values are separated with colons :, and each key-value pair is separated by commas ,
The spacing in this example is just to make it look nice - you don't have to do any indenting or newlines.
cs_dept_phonebook = {
"Porter" : "3041",
"Case" : "4618",
"Klinge" : "4599",
"Manley" : "2177",
"Urness" : "2188",
"Rieck" : "3795"
}
Accessing a value is the same as with a list, but you can put anything inside the [ ] brackets.
cs_dept_phonebook["Manley"]
cs_dept_phonebook["Urness"] = "2118"
cs_dept_phonebook
You can assign a value to a new key that isn't in the dictionary yet, and it will add it.
cs_dept_phonebook["Moore"] = "5555"
print(cs_dept_phonebook)
They're not considered ordered - you can't guarantee what order they'll be displayed in.
Delete dictionary elements with pop() method
cs_dept_phonebook.pop("Rieck")
print(cs_dept_phonebook)
Exercise 1: Write a program that asks the user for a name and phone number and then adds that to the phonebook.
name = input("Enter a name: ")
number = input("Enter a phone number: ")
#fill in the blank here
Exercise 2: Write a program to ask the user for a name and then display the phone number in the phone book for that name. What happens is they enter a name that isn't in the phone book? Come up with an idea for how that can be handled (Hint: experiment using an if statement and the in operator)
name = input("Enter a name: ")
#fill in the blank here
Keys can be anything of any type (though they are usually strings)
Values can be anything - even other containers like lists or other dictionaries
math_dict = { 3.14 : "This is an approximation of pi.",
1 : "This is the number 1",
2.718 : "This is an approximation of the natural log base.",
(0,0) : "This is the origin in two-dimensional space",
"zero" : 0,
"Fibonacci sequence" : [1,1,2,3,5,8,13,21,34] }
print(math_dict[3.14])
print(math_dict[1])
print(math_dict[(0,0)])
print(math_dict["zero"])
print(math_dict["Fibonacci sequence"])
You can loop through a dictionary with a for loop, though it will only run through each of the keys. You can then use the key to get the value.
for key in cs_dept_phonebook:
print(key,"'s office phone extension is",cs_dept_phonebook[key])