A
It is possible to use a recurring function:def set_value(d):
if not isinstance(d, dict):
return d
if d.get("value"):
return d
r = [x.get("value") for x in b_dict["values"] if x.get("id") == d.get("id")]
if r and r[0]:
d["value"] = r[0]
return d
def apply_recursive(func, obj):
if isinstance(obj, list):
return [apply_recursive(func, elem) for elem in obj]
elif isinstance(obj, dict):
obj = func(obj)
return {k: apply_recursive(func, v) for k, v in obj.items()}
else:
return func(obj)
challenge:_ = apply_recursive(set_value, a_dict)
result:In [106]: a_dict
Out[106]:
{'tests': [{'id': 1, 'title': 'S', 'value': 'passed'},
{'id': 2, 'title': 'D', 'value': 'failed'},
{'id': 3,
'title': 'P',
'value': 'failed',
'values': [{'id': 31,
'title': 'M',
'value': 'passed',
'values': [{'id': 311,
'title': 'P',
'values': [{'id': 3111, 'title': 'f', 'value': 'passed'},
{'id': 3112, 'title': 'f', 'value': ''}],
'value': 'passed'}]},
{'id': 32,
'title': 'S',
'value': '',
'values': [{'id': 321,
'title': 'P',
'values': [{'id': 3211, 'title': 's', 'value': 'passed'},
{'id': 3212, 'title': 'h', 'value': 'passed'}],
'value': 'failed'}]}]},
{'id': 4,
'title': 'S',
'value': 'passed',
'values': [{'id': 41, 'title': 'C', 'value': 'failed'},
{'id': 42, 'title': 'I', 'value': 'passed'}]}]}