这是我的字典列表:
array_of_dictionaries = [{
"name": "Budi",
"age": 23,
"test_scores": [100.0, 98.0, 89.0]
},
{
"name": "Charlie",
"age": 24,
"test_scores": [90.0, 100.0]
}]
这是我的代码:
def add_student(dictionary_list, student_dictionary):
for element in dictionary_list:
dict_copy = student_dictionary.copy()
dictionary_list.append(dict_copy)
return student_dictionary
updated_dictionary = add_student(array_of_dictionaries, { "name": "Doddy", "age": 13, "test_scores": [100.0, 100.0, 100.0] })
print(updated_dictionary)
我想要的结果是:
[{'name': 'Budi', 'age': 10, 'test_scores': [100.0, 98.0, 89.0]}, {'name': 'Charlie', 'age': 12, 'test_scores': [90.0, 100.0]}, {'name': 'Doddy', 'age': 13, 'test_scores': [100.0, 100.0, 100.0]}]
但我得到的是:
{'name': 'Doddy', 'age': 13, 'test_scores': [100.0, 100.0, 100.0]}
你的代码很混乱。最终,您要做的是将元素附加到列表中
即
要追加的元素是dictionary类型,而不是integer,但这不会影响逻辑。该函数的代码非常简单:
这将提供所需的输出。(当然,它不会复制要添加的词典的副本,但您可以通过添加
student_dictionary.copy()
来修改此行为)如果要在同一个字典上执行更新,则不需要函数。您可以直接添加元素
使用带有可变对象的copy命令时要小心,否则您将看到意外的行为
相关问题 更多 >
编程相关推荐