python - 将新字典添加到字典 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]}
解决方案
如果要对同一字典执行更新,则不需要函数。您可以直接添加元素。
newitem = { "name": "Doddy", "age": 13, "test_scores": [100.0, 100.0, 100.0] }
array_of_dictionaries.append(newitem)
小心使用带有可变对象的复制命令,否则您会看到意外行为。
推荐阅读
- excel - ActiveWorkbook.Close 在 Excel 365 中无法正常工作
- yaml - CloudFormation ImportValue、Join 和 Ref 中的链函数
- jquery - 减少滚动时的射击以获得更好的性能?
- java - 如何使 BigDecimal 除法更精确
- c# - 如果打开任务管理器,来自 user32.dll 的 SendInput 函数将不起作用
- highcharts - Highchart 饼图颜色没有变化
- python - python manage.py runserver 无法在 localhost:8000 上运行
- raspberry-pi - 接近树莓派的gpio寄存器地址,为什么unsigned int*和char*的结果不一样?
- java - Java JOOQ 多表查询
- oauth - WSO2-IS 5.10.0 - 服务提供者 - OAuthAdminServiceIdentityOAuthAdminException