Here is my list of dicts:
[{'subtopic': 'kuku',
'topic': 'lulu',
'attachments': ['ttt'],
'text': 'abc'},
{'subtopic': 'tutu',
'topic': 'lulu',
'attachments': ['pipu'],
'text': 'bubb'},
{'subtopic': 'did',
'topic': 'lulu',
'attachments': ['ktop'],
'text': 'gfg'},
{'subtopic': 'polo',
'topic': 'lulu',
'attachments': ['vuvu'],
'text': 'prolo'},
{'subtopic': 'ssd',
'topic': 'lulu',
'attachments': ['jkjk'],
'text': 'vint'},
{'subtopic': 'plp',
'topic': 'lulu',
'attachments': ['fre'],
'text': 'viw'},
{'subtopic': 'prw',
'topic': 'kll',
'attachments': [],
'text': 'kkk'},
{'subtopic': 'prw',
'topic': 'kll',
'attachments': [],
'text': 'fgfger2'}]
I would like to group by topic and subtopic to get a final result:
{
"lulu": {
"kuku": {
'attachments': ['sample'],
'text': ['sample']
},
"pupu": {
'attachments': ['sample'],
'text': ['sample']
},
"buru": {
'attachments': ['sample1',
'sample2'],
'text': ['sample1',
'sample2']
},
"titi": {
'attachments': ['sample'],
'text': ['sample']
},
"huhu": {
'attachments': ['sample'],
'text': ['sample']
}
},
"viriri": {
"vururur": {
'attachments': [],
'text': ['sample']
}
}
}
I am using:
groups = ['topic', 'subtopic', "text", "attachments"]
groups.reverse()
def hierachical_data(data, groups):
g = groups[-1]
g_list = []
for key, items in itertools.groupby(data, operator.itemgetter(g)):
g_list.append({key:list(items)})
groups = groups[0:-1]
if(len(groups) != 0):
for e in g_list:
for k, v in e.items():
e[k] = hierachical_data(v, groups)
return g_list
print(hierachical_data(filtered_top_facts_dicts, groups))
But getting an error for hashing lists. Please advise how to transform my json to the desired format.
To group the list of dictionaries by topic and subtopic, you can create an empty dictionary and then loop through the list of dictionaries to add each item to the appropriate nested level in the dictionary.
After this loop has completed, the result dictionary will be in the format you described, with topic and subtopic as the keys and the attachments and text as the values within each sub-dictionary.
Output: