无法在Python

时间:2016-10-01 22:49:09

标签: python dictionary keyerror

我是Python的新手,我们有一个使用词典和泡菜的作业。我们不得不制作一个简单的电话簿应用程序,但我收到一个我无法弄清楚的关键错误 除了第一个“查找条目”之外,大多数选项都有效。它提示我输入一个名字(我之前曾经腌过)我收到了这个错误:

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'

我已经厌倦了为密钥编写不同的东西,我也尝试使用phonebook_dict而不是info_dict,但我继续收到KeyError。通常情况下,我会通过PythonTutor运行它来捕获我的错误,但由于它使用的是字典和unpickling,我不能。也许我正在思考它或者看一些明显的东西,但我真的很感激任何见解。

以下是代码:

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)."

另外,phonebook.pickle供参考:

(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'

再一次,非常感谢任何帮助!

2 个答案:

答案 0 :(得分:3)

你很接近,你需要检查姓名是否在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

答案 1 :(得分:1)

您错过了if区块的缩进。

if name in info_dict: #how do i fix this?
#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"])

应该是:

if name in info_dict: #how do i fix this?
    #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"])

如果没有缩进,那些print语句将始终运行,这意味着它将尝试索引您的字典,无论name是否在字典中。