Python Programming Dictionaries

Dictionaries have keys and values. The keys are used to find the values. Here is an
example of a dictionary in use:

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
numbers = {}
menu_choice = 0
print_menu()
while menu_choice != 5:
menu_choice = input(“Type in a number (1-5):”)
if menu_choice == 1:
print “Telephone Numbers:”
for x in numbers.keys():
print “Name: “,x,” \tNumber: “,numbers[x]
print
elif menu_choice == 2:
print “Add Name and Number”
name = raw_input(“Name:”)
phone = raw_input(“Number:”)
numbers[name] = phone
elif menu_choice == 3:
print “Remove Name and Number”
name = raw_input(“Name:”)
if numbers.has_key(name):
del numbers[name]
else:
print name,” was not found”
elif menu_choice == 4:
print “Lookup Number”
name = raw_input(“Name:”)
if numbers.has_key(name):
print “The number is”,numbers[name]
else:
print name,” was not found”
elif menu_choice != 5:
print_menu()

And here is my output:

1.
2.
3.
4.
5.
Print Phone Numbers
Add a Phone Number
Remove a Phone Number
Lookup a Phone Number
Quit
Type in a number (1-5):2
Add Name and Number
Name:Joe
Number:545-4464
Type in a number (1-5):2
Add Name and Number
Name:Jill
Number:979-4654
Type in a number (1-5):2
Add Name and Number
Name:Fred
Number:132-9874
Type in a number (1-5):1
Telephone Numbers:
Name: Jill
Number: 979-4654
Name: Joe
Number: 545-4464
Name: Fred
Number: 132-9874
Type in a number (1-5):4
Lookup Number
Name:Joe
The number is 545-4464
Type in a number (1-5):3
Remove Name and Number
Name:Fred
Type in a number (1-5):1
Telephone Numbers:
Name: Jill
Number: 979-4654
Name: Joe
Number: 545-4464
Type in a number (1-5):5

Advertisements
Post a comment or leave a trackback: Trackback URL.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: