使用 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)
大卫

您需要为电话和电子邮件创建一个列表,然后附加到它:

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)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

使用 Append 时不会将值添加到列表中

如何不使用'append()'将新值添加到列表中,然后将值存储在新创建的列表中?

如何使用函数将新的键和值添加到列表的字典中

使用列表理解将 1 添加到字典中的值

使用append将新值添加到slice中,并且slice的所有值均已更改

使用 JQuery append 将 JSON 项添加到 HTML

我不能使用 .append() 将值附加到带有 python 的字典中

将 Tkinter 按钮添加到不带 .append 的列表中

如何使用 SQLAlchemy 將新字典添加到字典列表中

python append未添加到列表

如何通过使用列表的索引作为键和列表的项作为值来将列表添加到字典中?

Python:使用旧项目将新项目添加到列表的字典中

如何使用附加功能或其他功能将字典添加到列表中?

使用JSON修补程序将值添加到字典中

如何使用 for 循环将键和值添加到字典中

使用for循环将键和值添加到空字典中

在Python3中,如何使用.append函数将字符串添加到抓取链接?

使用循环将值添加到字典键

使用枚举键将值添加到Swift字典

使用while循环将值添加到字典

使用元组将值添加到字典键

如何使用AngularFire将项目添加到列表中某个项目内的特定词典中?

如何使用 Flutter 将 Json 中的值添加到列表对象中?

如何使用lapply将向量中每个数字的值添加到DF列表中

如何将输入中的值和使用 JS 创建的元素添加到列表中?

使用union将字典添加到`set()`中

使用xelement将结果添加到字典中

使用递归将项目添加到字典中

如何使用javascript将字符串添加到for循环内的列表中?