将新词典添加到词典列表中

2024-10-01 22:27:24 发布

您现在位置: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]}

Tags: ofnametestaddagedictionaryarraystudent
2条回答

你的代码很混乱。最终,您要做的是将元素附加到列表中

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

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

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

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

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

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

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

相关问题 更多 >

    热门问题