python - 访问嵌套字典的元素,该元素位于其他几个字典的列表中
问题描述
我正在遍历一个非常大的嵌套字典(最初是 json)来重命名一些键。目前,我设法逐一遍历列表中字典中列表的每个元素(它在另一个字典中)。对于主字典 (json) 中的每个项目,列表中的元素数量是不同的。
以下工作但不可扩展。
for el in a:
el['name']['info'][0]['details'] = el['name']['info'][0].pop('DT')
el['name']['info'][1]['details'] = el['name']['info'][1].pop('DT')
我也试过这个,它似乎不起作用:
for el in a:
el['name']['info']['details'] = el['name']['info'].pop('DT')
我可以在那里写一些东西来将更改应用于这些字典列表中的所有元素吗?
解决方案
扩展 TrebledJ 在他的评论中所说的话会给你类似的东西:
a = [{
'name': {
'info': [
{'DT': 'abc'},
{'DT': 'def'}
]
}
}]
print(a)
for el in a:
for info_el in el['name']['info']:
info_el['details'] = info_el.pop('DT')
print(a)
有输出:
[{'name': {'info': [{'DT': 'abc'}, {'DT': 'def'}]}}]
[{'name': {'info': [{'details': 'abc'}, {'details': 'def'}]}}]
推荐阅读
- excel - AVERAGEIF() 语句中的上限值
- tensorflow - Keras 的 CNN 培训冻结
- javascript - 在 C/C++ 和 javascript 应用程序之间共享大浮点数组
- javascript - 提示用户输入,感谢他们输入 Javascript
- mysql - SQL Fiddle - 无法添加外键约束
- regex - 正则表达式打括号,但只能以特定方式
- javascript - 将颜色信息添加到复选框文件夹 dat.gui
- sql - 从多列中选择 IN
- purescript - Purescript Halogen 在表单之外手动触发输入验证
- algorithm - 将 Bellman-Ford 改进为线性运行时间