Reputation: 149
I am looping through a very large nested dictionary (originally json) to rename some of the keys. At the moment I managed to loop through each element of the list inside the dictionary that is in the list (it is inside one more dictionary) one by one. The number of elements in the list is different for each of the items in the main dictionary (json).
The below works but is not scaleable.
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')
I also tried this, it doesn't work it seems:
for el in a:
el['name']['info']['details'] = el['name']['info'].pop('DT')
Is there something I could write there that would apply the changes to all the elements in the list of these dictionaries?
Upvotes: 0
Views: 37
Reputation: 624
Expanding upon what TrebledJ said in his comment would give you something like:
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)
has the output:
[{'name': {'info': [{'DT': 'abc'}, {'DT': 'def'}]}}]
[{'name': {'info': [{'details': 'abc'}, {'details': 'def'}]}}]
Upvotes: 1