2 回答

TA贡献1785条经验 获得超8个赞
您需要为电话和电子邮件创建一个列表,然后附加到它:
def add_contact(friends):
contact = {}
contact["name"]=input("name: ")
contact["phone"] = []
contact["mail"] = []
for i in range(2):
contact["phone"].append(input("phone: "))
for i in range(2):
contact["mail"].append(input("mail: "))
contact["street"]=input("street: ")
contact["housenum"]=input("housenum: ")
contact["cp"]=input("cp: ")
contact["city"]=input("city: ")
friends.append(contact)
friends = [{"name":[{"telf":[0]*2},{"mail":[0]*2},
{"street":"","housenum":"","cp":"", "city":""}]}] #This is the list im creating to fill it with friends information, the first dictionary in the list is an empty dictionary which i dont want to print.
add_contact(friends)
print(friends)

TA贡献1827条经验 获得超4个赞
你的解决方案的问题在于你试图为不存在的东西增加价值。
当你联系[“电话”]时。这会在字典联系人中创建一个键。{"Phone":} 但问题是你确实联系了["phone"][i]。所以在这个键中搜索第 i 个元素。哪个不存在。因此你得到错误。所以你首先需要将列表添加到这个字典中。那么只有你可以添加多个数字
def add_contact(friends):
contact = {}
contact["name"]=input("name: ")
contact["phone"] = []
contact["mail"] = []
for i in range(2):
contact["phone"].append(input("phone: "))
for i in range(2):
contact["mail"].append(input("mail: "))
contact["street"]=input("street: ")
contact["housenum"]=input("housenum: ")
contact["cp"]=input("cp: ")
contact["city"]=input("city: ")
friends.append(contact)
friends = [{"name":[{"telf":[0]*2},{"mail":[0]*2},
{"street":"","housenum":"","cp":"", "city":""}]}] #This is the list im creating to fill it with friends information, the first dictionary in the list is an empty dictionary which i dont want to print.
add_contact(friends)
print(friends)
添加回答
举报