I have a json format data in a list like below:-
lis_t=[{'score': 76, 'steps': [{'score': 49, 'len': 261}, {'score': 27, 'len': 172}, {'score': 0, 'len': 0}]},
{'score': 82,'steps': [{'score': 82, 'len': 484}, {'score': 0, 'len': 0 }]},
{'score': 51, 'steps': [{'score': 51, 'len': 268}, {'score': 0, 'len': 0},{'score': 16, 'len': 75}, {'score': 187, 'len': 47}]}]
From this list I want to add a new key details
in the value of key steps
and append only the score
key as a value
to the new key. The output I am excepting is as follow:-
output =[{'score': 76, 'steps': [{'details':{'score': 49}, 'len': 261,'details': {'score': 27}, 'len': 172,'details': {'score': 0}, 'len': 0}]},
{'score': 82, 'steps': [{'details':{'score': 82}, 'len': 484, 'details':{'score': 0}, 'len': 0 }]},
{'score': 51, 'steps': [{'details':{'score': 51}, 'len': 268,'details': {'score': 0}, 'len': 0,'details':{'score': 16}, 'len': 75, 'details':{'score': 187}, 'len': 47}]}]
Now, I tried to create a new key details
and tried to append the value
but it says that the dictionary size is changed while iterating
. To avoid this I have used list(j.keys())
but if I use this then I wont be able to access the value of that dictionary. Is there any better way of solving this issue?
for i in lis_t:
for k,v in i.items():
if k == 'steps':
for j in v:
for key,val in j.items():
j['details']=val
print(key)
Error:
RuntimeError: dictionary changed size during iteration
Excepted Output:-
output=[{'score': 76, 'steps': [{'details':{'score': 49}, 'len': 261,'details': {'score': 27}, 'len': 172,'details': {'score': 0}, 'len': 0}]},
{'score': 82, 'steps': [{'details':{'score': 82}, 'len': 484, 'details':{'score': 0}, 'len': 0 }]},
{'score': 51, 'steps': [{'details':{'score': 51}, 'len': 268,'details': {'score': 0}, 'len': 0,'details':{'score': 16}, 'len': 75, 'details':{'score': 187}, 'len': 47}]}]
CodePudding user response:
I would use a list comprehension to reset the "steps" value. Maybe something like:
lis_t = [
{
'score': 76,
'steps': [
{'score': 49, 'len': 261},
{'score': 27, 'len': 172},
{'score': 0, 'len': 0}
]
},
{
'score': 82,
'steps': [
{'score': 82, 'len': 484},
{'score': 0, 'len': 0 }
]
},
{
'score': 51,
'steps': [
{'score': 51, 'len': 268},
{'score': 0, 'len': 0},
{'score': 16, 'len': 75},
{'score': 187, 'len': 47}
]
}
]
for item in lis_t:
item["steps"] = [
{"details": {"score": step_item["score"]}, "len": step_item["len"]}
for step_item in item["steps"]
]
import json
print(json.dumps(lis_t))
This gives:
[
{
"score": 76,
"steps": [
{"details": {"score": 49}, "len": 261},
{"details": {"score": 27}, "len": 172},
{"details": {"score": 0}, "len": 0}
]
},
{
"score": 82,
"steps": [
{"details": {"score": 82}, "len": 484},
{"details": {"score": 0}, "len": 0}
]
},
{
"score": 51,
"steps": [
{"details": {"score": 51}, "len": 268},
{"details": {"score": 0}, "len": 0},
{"details": {"score": 16}, "len": 75},
{"details": {"score": 187}, "len": 47}
]
}
]
Which is what I think you are after.