Home > Enterprise >  Create a dictionnary from defaultdict(list) with nested list inside
Create a dictionnary from defaultdict(list) with nested list inside

Time:09-08

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.

CodePudding user response:

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']}]}]
  • Related