Home > Software design >  How to create a dictionary from a nested list of dictionary
How to create a dictionary from a nested list of dictionary

Time:09-17

I have a dictionary in a nested list as below. I want to create a new dictionary with keys and values from my original dictionary

my_dict= {'mc' : [[{'id': '1.185662381',
        'marketDefinition': {'bspMarket': False,
         'turnInPlayEnabled': True,
         'persistenceEnabled': True,
         'marketBaseRate': 5.0,
         'eventId': '30729399',
         'eventTypeId': '1',
         'numberOfWinners': 1,
         'bettingType': 'ODDS'}}],
    [{'id': '1.185662380',
        'marketDefinition': {'bspMarket': True,
         'turnInPlayEnabled': False,
         'persistenceEnabled': True,
         'marketBaseRate': 5.0,
         'eventId': '30729399',
         'eventTypeId': '1',
         'numberOfWinners': 1,
         'bettingType': 'ODDS'}}]]}

My expected output should look like this

new_dict = {'id':['1.185662380',1.185662381],
             bspMarket:[False,True],
            turnInPlayEnabled: [True,False]
              .....}

Here is what I have tried but It is not working rightly from my end. Any help would be greatly appreciated.

create_dict = {}
for index, arr in enumerate(my_dict):
    for arr2 in arr:
       create_dict['id'] = arr2['id]
       create_dict['bspMarket'] = arr2['marketDefinition']['bspMarket]
       create_dict['turnInPlayEnabled'] = arr2['marketDefinition']['iturnInPlayEnabled]

The above looping conditions only create a dictionary with the first element in the list. that is the element at position zero

CodePudding user response:

You're overwriting the resulting dictionary elements each time through your loop, not making lists and appending to them. You can use a defaultdict() to automatically create the lists as needed.

from collections import defaultdict

new_dict = defaultdict(list)
for l in my_dict['mc']:
    for d in l:
        new_dict['id'].append(d['id'])
        for k, v in d['marketDefinition'].items():
            new_dict[k].append(v)
  • Related