Create a dictionnary from defaultdict(list) with nested list inside

Question:

I have a deafaultdict(list) in the following format:

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

And I need to create another dictionary with an additional level:

{
    't':'t0',
    'cats': [
        {
            'cat': 'cat0',
            'eagles':['eagle0']
        },
        {
            'cat': 'cat1',
            'eagles: ['eagle1]'
        }
    ]
} ...

I tried to implement the answer from Output an existing defaultdict into appropriate JSON format for flare dendogram?, but I can’t get how to add this additional group for ‘cats’:

for k, v in d.items():
    my_dict = {
         't': k,
        'cats': [{'cat': v}]
     }

with output like:

{'t': 't0', 'cats':[{'cat': [['cat1', ['eagle1']]]}]}

Thank you in advance.

Asked By: Daria Muller

||

Answers:

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']}]}]
Answered By: Barmar
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.