[Solved] Create a dictionnary from defaultdict(list) with nested list inside [closed]


Just loop through your dictionary elements, reformatting the list of lists into list of dictionary using a list comprehension.

original = {
    't0': [['cat0', ['eagle0']], ['cat1', ['eagle1']]],
    't1': [['cat2', ['eagle2', 'eagle3']]]
}

result = []
for key, cats in original.items():
    cats = [{'cat': cat, 'eagles': eagles} for cat, eagles in cats]
    result.append({'t': key, 'cats': cats})

print(result)

Output:

[{'t': 't0', 'cats': [{'cat': 'cat0', 'eagles': ['eagle0']}, {'cat': 'cat1', 'eagles': ['eagle1']}]}
,{'t': 't1', 'cats': [{'cat': 'cat2', 'eagles': ['eagle2', 'eagle3']}]}]

1

solved Create a dictionnary from defaultdict(list) with nested list inside [closed]