This document provides an introduction to dictionaries in Python. It explains that dictionaries are collections of key-value pairs that allow users to store, query, add, update, and delete information. It shows how to initialize an empty dictionary and populate it with initial key-value pairs. It also demonstrates how to query, add, update, and delete key-value pairs from a dictionary. Finally, it provides a phone book example to demonstrate using dictionaries in a practice program.
9. Update
• Update the content of the dictionary
• aDict.update(<dict>)
• Example:
>>> aDict.update({'apple':5})
>>> aDict.update({'chocolate':10})
>>> aDict
{'chocolate': 10, 'apple': 5, 'banana': 5}
Dictionary
Introduction
10. Delete
• Remove a item from the dictionary
• del aDict[“apple”]
Dictionary
Introduction
11. Practice
• Phone book
• Functions:
• Print a phone number
• Add a phone number
• Remove a phone number
• Lookup a phone number
Dictionary
Introduction
12. Practice
def print_menu():
print('1. Print Phone Numbers')
print('2. Add a Phone Number')
print('3. Remove a Phone Number')
print('4. Lookup a Phone Number')
print('5. Quit')
print()
Dictionary
Introduction
13. Practice
numbers = {}
menu_choice = 0
print_menu()
while menu_choice != 5:
menu_choice = int(input("Type in a number (1-5): "))
if menu_choice == 1:
pass
elif menu_choice == 2:
pass
elif menu_choice == 3: http://goo.gl/A9xDr
pass
elif menu_choice == 4:
pass
elif menu_choice != 5:
print_menu()
Dictionary
Introduction
14. Print
if menu_choice == 1:
print("Telephone Numbers:")
for x in numbers.keys():
print("Name: ", x, "tNumber:", numbers[x])
print()
Dictionary
Introduction
15. Add
elif menu_choice == 2:
print("Add Name and Number")
name = input("Name: ")
phone = input("Number: ")
numbers[name] = phone
Dictionary
Introduction
16. Remove
elif menu_choice == 3:
print("Remove Name and Number")
name = input("Name: ")
if name in numbers:
del numbers[name]
else:
print(name, "was not found")
Dictionary
Introduction
17. Lookup
elif menu_choice == 4:
print("Lookup Number")
name = input("Name: ")
if name in numbers:
print("The number is", numbers[name])
else:
print(name, "was not found")
Dictionary
Introduction