How to iterate and append key value pairs from a dictionary within a dicionary and storing values with same key into a list python
A recursive approach works well here.
You can iterate over data
and call a recursive function merge
which takes a dictionary d
and merges it into another dictionary merged
on matching keys. Each dict
value in d
results in another recursive call, while other values get appended to the value of the corresponding key.
def merge(d, merged):
for k, v in d.items():
if isinstance(v, dict):
merge(v, merged.setdefault(k, {}))
else:
merged.setdefault(k, []).append(v)
out = {}
for d in data:
merge(d, out)
Output:
{'fields': {'issuetype': {'id': ['23434', '11200'],
'name': ['Food', 'House'],
'self': ['www.google.com/23434', 'www.google.com/issuetype/11200']},
'priority': {'id': ['12345', '123400'],
'name': ['Dessert', 'Nonessential'],
'self': ['www.google.com/12345', 'www.google.com/priority/123400']},
'status': {'id': ['15432', '10035'],
'name': ['To Do', 'To Do'],
'self': ['www.google.com/status/15432', 'www.google.com/status/10035'],
'statusCategory': {'id': [2, 2],
'key': ['new', 'new'],
'name': ['To Do', 'To Do'],
'self': ['www.google.com/statuscategory/2',
'www.google.com/statuscategory/2']}},
'summary': ['PL-Bus-ICD-1882', 'PL-Bus-ICD-1885']},
'id': ['12356', '34262'],
'key': ['eed-1234', 'ekr-1254'],
'self': ['www.google.com/issue/12356', 'www.google.com/issue/34262']}