首页 > 解决方案 > 将新字典添加到字典 python 列表中

问题描述

所以这是我的字典列表:

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]}

标签: python

解决方案


如果要对同一字典执行更新,则不需要函数。您可以直接添加元素。

newitem = { "name": "Doddy", "age": 13, "test_scores": [100.0, 100.0, 100.0] }
array_of_dictionaries.append(newitem)

小心使用带有可变对象的复制命令,否则您会看到意外行为。


推荐阅读