为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

翻过高山走不出你 2021-09-02 20:57:54
我正在尝试创建一个朋友词典,我可以在其中添加一个朋友并将他的信息放在那里。我想用朋友的名字作为钥匙,两个号码,两封电子邮件和他住在哪里的信息。我的问题是我的程序在询问数字和电子邮件时崩溃,我不知道我做错了什么。我使用了 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)
查看完整描述

2 回答

?
慕的地10843

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)


查看完整回答
反对 回复 2021-09-02
?
GCT1015

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)


查看完整回答
反对 回复 2021-09-02
  • 2 回答
  • 0 关注
  • 314 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信