Home > OS >  Converting two complex dictionary list to a dictionary
Converting two complex dictionary list to a dictionary

Time:11-18

suppose I have two dictionary list below:

  all=[]
  lis1={
    'code':'matata',
    'commandes':[
        {
            'date':'12-10-22',
            'content':[
                {
                    'article':'Article1',
                    'designation':'Designe1',
                    'quantity':5
                }
            ]
         }
      ]
    }
 
 lis2={
     'code':'fropm',
     'commandes':[
       {
        'date':'04-08-21',
        'content':[
            {
                'article':'Article2',
                'designation':'Designe2',
                'quantity':3
            }
         ]
       }
     ]
   }

Now I add at list level my two dictionaries

all.append(list1)
all.append(liste2)

to replace the [..] in {..} for a single list we can do all[0] But after adding the two lists and then doing all[0] we only have the first list whose [..] whose square brackets are replaced by {..} I would like to have this rendering { {...}, {...} }

Is this possible??

CodePudding user response:

You need to refine what you are trying to accomplish. lis1 is a dict, not a list. lis1['commandes'] is a list containing a single dict, but presumably in the general case it might have more. Each of those has a key "date" and another key "content", which is again a list of dicts ....

An arbitrary example would be to add the commandes from lis2 to those in lis1:

lis1['commandes'].extend(  lis2['commandes'] )

which is using the list .extend() method to join two lists. It should yield

{
'code':'matata',
'commandes':[
    {
        'date':'12-10-22',
        'content':[
            {
                'article':'Article1',
                'designation':'Designe1',
                'quantity':5
            }
        ]
     },
     {
        'date':'04-08-21',
        'content':[
            {
                'article':'Article2',
                'designation':'Designe2',
                'quantity':3
            }
        ]
     }
  ]
}

"Drilling down" is just a matter of supplying array indices and dict keys as appropriate. for example,

lis1['commandes'][0]['content'][0]['quantity']

will be 5.

  • Related