Dictionaries in Python, are used to store data values in key:value pairs. Each value stored in a dictionary can be accessed using a key, which is any type of object (a string, a number, a list, etc.) instead of using its index on address it.
For example, a database of phone numbers could be stored using a dictionary like this:
phonebook = {}
phonebook["John"] = 938477566
phonebook["Jack"] = 938377264
phonebook["Jill"] = 947662781
print(phonebook)
Alternatively, a dictionary can be initialized with the same values in the following notation:
phonebook = {
"John" : 938477566,
"Jack" : 938377264,
"Jill" : 947662781
}
print(phonebook)
Iterating over dictionaries
Dictionaries can be iterated over, just like a list. However, a dictionary, unlike a list, does not keep the order of the values stored in it. To iterate over key value pairs, use the following syntax:
phonebook = {"Raymond" : 938477566,"Ivan" : 938377264,"Rich" : 947662781}
for name, number in phonebook.items():
print("Phone number of %s is %d" % (name, number))
Removing a value
To remove a specified index, use either one of the following notations:
phonebook = {
"Raymond" : 938477566,
"Ivan" : 938377264,
"Rich" : 947662781
}
del phonebook["Raymond"]
print(phonebook)
OR:
phonebook = {
"Raymond" : 938477566,
"Ivan" : 938377264,
"Rich" : 947662781
}
phonebook.pop("Raymond")
print(phonebook)
Exercise
Add "Mike" to the phonebook with the phone number 938273443, and remove Rich from the phonebook.
phonebook = {
"Raymond" : 938477566,
"Ivan" : 938377264,
"Rich" : 947662781
}
# your code goes here
# testing code
if "Mike" in phonebook:
print("Mike is listed in the phonebook.")
if "Rich" not in phonebook:
print("Rich is not listed in the phonebook.")
phonebook = {
"Raymond" : 938477566,
"Ivan" : 938377264,
"Rich" : 947662781
}
# your code goes here
phonebook["Mike"] = 938273443
del phonebook["Rich"]
# testing code
if "Mike" in phonebook:
print("Mike is listed in the phonebook.")
if "Rich" not in phonebook:
print("Rich is not listed in the phonebook.")
test_output_contains("Mike is listed in the phonebook.")
test_output_contains("Rich is not listed in the phonebook.")
success_msg("Excellent!")