在我的介绍comp sci 课程的最后几天,我们开始创建字典。我们书中的一个家庭作业程序要求我们创建一些可以查找、添加、更改和删除一组姓名和电子邮件地址的东西。它要求我们腌制字典,但对我来说更重要的是它规定每次程序启动时,它都应该从文件中检索字典并取消腌制它。我不知道我是否将自己编码到一个角落,但我无法弄清楚如何用我迄今为止所做的事情来做到这一点。
我的代码:
import mMyUtils
import pickle
LOOK_UP = 1
ADD = 2
CHANGE = 3
DELETE = 4
QUIT = 5
def main():
emails = {}
choice = 0
while choice != QUIT:
choice = getMenuChoice()
if choice == LOOK_UP:
lookUp(emails)
elif choice == ADD:
add(emails)
elif choice == CHANGE:
change(emails)
elif choice == DELETE:
delete(emails)
else:
exit
def getMenuChoice():
print()
print('Name and Email Address Catalog')
print('------------------------------')
print('1. Look up an email address')
print('2. Add a new email address')
print('3. Change an email address')
print('4. Delete an email address')
print('5. Quit the program')
print()
choice = int(input('Enter the choice: '))
while choice < LOOK_UP or choice > QUIT:
choice = int(input('Enter a valid choice: '))
return choice
def lookUp(emails):
name = input('Enter a name: ')
print(emails.get(name, 'Not found.'))
def add(emails):
name = input('Enter a name: ')
address = input('Enter an email address: ')
if name not in emails:
emails[name] = address
pickle.dump(emails, open("emails.dat", "wb"))
else:
print('That entry already exists.')
def change(emails):
name = input('Enter a name: ')
if name in emails:
address = input('Enter the new address: ')
emails[name] = address
pickle.dump(emails, open("emails.dat", "wb"))
else:
print('That name is not found.')
def delete(emails):
name = input('Enter a name: ')
if name in emails:
del emails[name]
else:
print('That name is not found.')
main()
我知道我应该将我的 emails 变量设置为某种形式的 pickle.load,但我一生都无法弄清楚。mMyUtils 是我为 try/except 逻辑创建的库,一旦我得到新的东西,我就会把它放进去。