Search code examples
pythondictionarykeyerror

Trouble hitting the correct dictionary key in Python


I'm new to Python and we have an assignment working with dictionaries and pickles. We had to make a simple phonebook app, but I'm receiving a key error that I can't figure out.
Most of the options work, except for the first "Look up an entry". It prompts me for a name (that I have previously pickled) I receive this error:

Traceback (most recent call last):
  File "phonebook.py", line 95, in <module>
    look_up()
  File "phonebook.py", line 25, in look_up
    info_dict = phonebook_dict[name]
KeyError: 'lelani'

I've tired writing different things for the keys and I've also tried using phonebook_dict instead of info_dict but I continue to receive a KeyError. Normally, I would run this through PythonTutor to catch my error, but since it's using dictionaries and unpickling, I can't. Maybe I'm overthinking it or looking over something obvious, but I would really appreciate any insight.

Here's the code:

from os.path import exists

filename = "phonebook2.pickle"

if exists('phonebook.pickle'):
    print "Loading phonebook"
    phonebook_file = open("phonebook.pickle", "r")
    phonebook_dict = pickle.load(phonebook_file)
    phonebook_file.close()

else:
    phonebook_dict = {}

while True:
    #Looks up an entry
    def look_up():
        name = raw_input("Name? ")
        info_dict = phonebook_dict[name]
        if name in info_dict: #how do i fix this?/ won't return set     contacts
        #info_dict = phonebook_dict[name]
            print "Found entry for %s: " % (name)
            print "Cell Phone Number: %s" % (info_dict["Cell"])
            print "Home Phone Number: %s" % (info_dict["Home"])
            print "Work Phone Number: %s" % (info_dict["Work"])

        else:
            print "Entry for %s not found." % name

#Sets an entry
def set_entry():
    print "Please add the name and number to create a new entry:"
    name = raw_input("Name: ").strip()
    cell_phone = raw_input("Cell Phone Number? ")
    home_phone = raw_input("Home Phone Number? ")
    work_phone = raw_input("Work Phone Number? ")
    info_dict = {
        "Cell": cell_phone,
        "Home": home_phone,
        "Work": work_phone}
    phonebook_dict[name] = info_dict
    print "Entry stored for %s" % name


#Deletes an entry
def delete_entry():
    print "Please enter a name to delete from the phonebook."
    name = raw_input("Name: ").lower()
    if name in phonebook_dict:
        del phonebook_dict[name]
        print "Deleted entry for %s" % name
    else:
        print "%s not found." % name

#Lists all entries
def list_entries():
    for name, info_dict in phonebook_dict.items():
        print "Found entry for %s: " % (name)
        print "*" * 30
        print "Cell Phone Number: %s" % (info_dict["Cell"])
        print "Home Phone Number: %s" % (info_dict["Home"])
        print "Work Phone Number: %s" % (info_dict["Work"])
        print "*" * 30


#Saves all entries
def save_entries():
    phonebook_file = open("phonebook.pickle", "w")
    pickle.dump(phonebook_dict, phonebook_file)
    phonebook_file.close()
    print "Entries saved to the phonebook."


print """
Electronic Phone Book
=====================

1\. Look up an entry
2\. Set an entry
3\. Delete an entry
4\. List all entries
5\. Save entries
6\. Quit
"""

menu_number = int(raw_input("What do you want to do (1-6)? "))

if menu_number == 1:
    look_up()
elif menu_number == 2:
    set_entry()
elif menu_number == 3:
    delete_entry()
elif menu_number == 4:
    list_entries()
elif menu_number == 5:
    save_entries()
elif menu_number == 6:
    print "Goodbye!"
    break
elif menu_number > 6:
    print "Invalid option. Please enter a valid option (1-6)."

Also, phonebook.pickle for reference:

(dp0
S'Autumn'
p1
(dp2
S'Cell'
p3
S'111-111-1111'
p4
sS'Home'
p5
S'222-222-2222'
p6
sS'Work'
p7
S'333-333-3333'
p8
ssS'Lelani'
p9
(dp10
g3
S'444-444-4444'
p11
sg5
S'555-555-5555'
p12
sg7
S'666-666-6666'

Again, any help is greatly appreciated!


Solution

  • You were close, you need to check if name is in the phonebook_dict

    def look_up():
        name = raw_input("Name? ")
        if name in phonebook_dict: 
            info_dict = phonebook_dict[name]
            print "Found entry for %s: " % (name)
            print "Cell Phone Number: %s" % (info_dict["Cell"])
            print "Home Phone Number: %s" % (info_dict["Home"])
            print "Work Phone Number: %s" % (info_dict["Work"])
    
        else:
            print "Entry for %s not found." % name