{'page_1': [{'useless': '73636763'},
{'good': 'info is good'},
{'good': 'info is also good'},
{'nice': 'info is nice'},
{'nice': 'info is also nice '}],
'page_2': [{'useless': '87465432'},
{'good': 'info is good on page 2'},
{'good': 'info is also good on page 2'},
{'nice': 'info is nice on page 2'},
{'nice': 'info is also nice on page 2'}]}
How do I sort this dict to look like this:
{
'page_1': [{'useless': '73636763'},
{'good': ['info is good', 'info is also good']},
{'nice': ['info is nice', 'info is also nice']}],
'page_2': [{'useless': '87465432'},
{'good': ['info is good on page 2', 'info is also good on page 2']},
{'nice': ['info is nice on page 2', 'info is also nice on page 2']}]
}
I have tried to use defaultdict
for this purpose but I not able to find a way to keep the keys page_1
and page_2
as:
for item in mydict:
for pair in mydict[item]:
for key, value in pair.items():
dict_from_collections[key].append(value)
dict_from_collections
is an empty defaultdict(list)
CodePudding user response:
You can convert the dict of lists of singleton dicts into a dict of dicts first, and then convert the sub-dicts to lists of singleton dicts:
output = {}
for page, lst in mydict.items():
for [(key, value)] in map(dict.items, lst):
output.setdefault(page, {}).setdefault(key, []).append(value)
for page, mapping in output.items():
output[page] = list(map(dict, zip(mapping.items())))
output
becomes:
{'page_1': [{'useless': ['73636763']}, {'good': ['info is good', 'info is also good']}, {'nice': ['info is nice', 'info is also nice ']}], 'page_2': [{'useless': ['87465432']}, {'good': ['info is good on page 2', 'info is also good on page 2']}, {'nice': ['info is nice on page 2', 'info is also nice on page 2']}]}