如何编写名为 update 的函数来更新字典中的内容?

问题描述 投票:0回答:1

我想在 python 中为列表创建名为 update 的函数,但我不知道如何做到这一点。

我尝试进行研究,但最常见的信息是显示如何通过简单的注释而不是功能来进行更改。

我的清单在这里:

students = {
 "student1": {"name": "John", "age": 21, "live" :"UK"}
 "student2": {"name":"Steve", "age":25, "live": "USE"}
 "student3": {"name":"Tom", "age":32, "live": "France "}
 "student4": {"name":"Josh", "age":31, "live": "Spain"}}

到目前为止,我尝试使用此代码进行更新,但它根本没有运行

def update_students(students, student_id ,name, age ,live):
    students[student_id]= students.update({"name" :name,"age":age, "live": live})
    return students, student_id ,name,age ,live
update_students(students,"student2","Alex", "32","japan ")

print(students)

但没有采取任何行动...我可以纠正什么?

在这种情况下如何准备功能删除?

有人可以帮我处理这段代码并解释一下为什么它是这样的吗?

python function dictionary lis
1个回答
0
投票

对存储在

.update()
的字典调用
students[student_id]
,而不是将其分配给返回值(即
None
)。

代码:

students = {
 "student1": {"name": "John", "age": 21, "live" :"UK"},
 "student2": {"name":"Steve", "age":25, "live": "USE"},
 "student3": {"name":"Tom", "age":32, "live": "France "},
 "student4": {"name":"Josh", "age":31, "live": "Spain"}
}
 
def update_students(students, student_id ,name, age ,live):
    students[student_id].update({"name" :name,"age":age, "live": live})
    return students, student_id ,name,age ,live
    
update_students(students,"student2","Alex", "32","japan ")

print(students)

输出:

{'student1': {'name': 'John', 'age': 21, 'live': 'UK'}, 'student2': {'name': 'Alex', 'age': '32', 'live': 'japan '}, 'student3': {'name': 'Tom', 'age': 32, 'live': 'France '}, 'student4': {'name': 'Josh', 'age': 31, 'live': 'Spain'}}
© www.soinside.com 2019 - 2024. All rights reserved.