无法在 Python 中输入正确的字典键
Trouble hitting the correct dictionary key in Python
我是 Python 的新手,我们的作业是处理字典和泡菜。我们必须制作一个简单的电话簿应用程序,但我收到一个我无法弄清楚的关键错误。
大多数选项都有效,除了第一个 "Look up an entry"。它提示我输入一个名字(我之前已经腌制过)我收到这个错误:
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'
再次感谢您的帮助!
您的 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"])
如果没有缩进,这些打印语句将始终 运行,这意味着无论 name
是否在字典中,它都会尝试为您的字典编制索引。
你很接近,你需要检查姓名是否在 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
我是 Python 的新手,我们的作业是处理字典和泡菜。我们必须制作一个简单的电话簿应用程序,但我收到一个我无法弄清楚的关键错误。
大多数选项都有效,除了第一个 "Look up an entry"。它提示我输入一个名字(我之前已经腌制过)我收到这个错误:
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'
再次感谢您的帮助!
您的 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"])
如果没有缩进,这些打印语句将始终 运行,这意味着无论 name
是否在字典中,它都会尝试为您的字典编制索引。
你很接近,你需要检查姓名是否在 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