使用 append 添加到字典内列表中的值

我正在尝试创建一个朋友词典,我可以在其中添加一个朋友并将他的信息放在那里。


我想用朋友的名字作为钥匙,两个号码,两封电子邮件和他住在哪里的信息。


我的问题是我的程序在询问数字和电子邮件时崩溃,我不知道我做错了什么。


我使用了 append 函数,因为每个朋友的号码都保存在一个列表中。我不想要一个我想修复我的新程序,所以我可以理解为什么它会失败。


我想做的另一件事是不打印我最后创建的空字典,它是一个包含字典的列表(每个朋友都是一个字典),所以我想我应该说从位置 1 到最后,但我想有更好的方法,在这里我发布我的代码,错误是当我要求第一个和第二个电话和邮件时。


def add_contact(friends):

    contact = {}

    contact["name"]=input("name: ")

    for i in range(2):

        contact["phone"][i]=input("phone: ") #Here it crashes

    for i in range(2):

        contact["mail"][i]=input("mail: ") #Here too


    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)


翻过高山走不出你
浏览 317回答 2
2回答

慕的地10843

您需要为电话和电子邮件创建一个列表,然后附加到它: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)

GCT1015

你的解决方案的问题在于你试图为不存在的东西增加价值。当你联系[“电话”]时。这会在字典联系人中创建一个键。{"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)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python