首页 > 解决方案 > 访问嵌套字典的元素,该元素位于其他几个字典的列表中

问题描述

我正在遍历一个非常大的嵌套字典(最初是 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')

我可以在那里写一些东西来将更改应用于这些字典列表中的所有元素吗?

标签: pythondictionary

解决方案


扩展 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'}]}}]

推荐阅读