将新字典添加到字典python列表中

时间:2020-09-06 13:22:40

标签: 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]}

2 个答案:

答案 0 :(得分:0)

您的代码非常混乱。最终,您要做的就是将元素添加到列表中。

l = [1, 2, 3]
l.append(4)
#l = [1, 2, 3, 4]

要附加的元素是字典类型,而不是整数,但这不会影响逻辑。该函数的代码非常简单:

def add_student(dictionary_list, student_dictionary):
  dictionary_list.append(student_dictionary)
  return dictionary_list

这将提供所需的输出。 (当然,它不会为要添加的字典提供副本,但是您可以通过附加student_dictionary.copy()来修改此行为)。

答案 1 :(得分:0)

如果要在同一词典上执行更新,则不需要功能。您可以直接添加元素。

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

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