我正试图在python 3.10中使用字典和列表制作联系人列表/电话簿,并一直试图添加一个功能来添加不在电话簿内的搜索联系人。我正在尝试的当前方法给了我"运行时错误:字典在迭代期间改变了大小",所以我需要找到一种方法来添加字典而没有for循环,或者有人有任何建议吗?我很抱歉,如果这是简单的,或者我做的很少,因为我刚刚开始独立学习如何编码。谢谢你提供的任何帮助。下面是错误产生的部分:
from collections import defaultdict
#contact list using collection module
book = defaultdict(list)
search = input('Enter the name of the person you are looking for: ')
for key, value in book.items():
if key.startswith(search):
print(key, value)
else:
new_contact = input('That person is not in your contacts. Would you like to add them?(yes = y and no = n)')
if new_contact == 'y':
add_info = input('What is their contact information?')
book[search].append(add_info)
else:
break
假设你有一个像这样的字典book
存在**book** = {'Alex' : 1234, 'Jane': 5694, ...}
这应该有帮助:
一般来说,循环一个可迭代对象(列表,字典)并改变数据不是一个好主意。
book = {'Bill': 3456, 'Jane': 1298}
search = input('Enter the name of the person you are looking for: ')
if search in book:
# found it - if type either "Bill" or "Jane"
print(search, book[search])
else: # anything else - not in the phonebook.
print(f'The {search} is not in the book')
action = input('That person is not in your contacts. Would you like to add them?(yes = y and no = n)')
if action == 'y':
add_info = input('What is the contact information? (name phone) ')
name, phone = add_info.split()
#book[name].append(phone) # this Won't work. "Missing key"!
book.get(name, phone)