Home > Enterprise >  Converting a complex dictionary list to a dictionary
Converting a complex dictionary list to a dictionary

Time:11-16

I would like to convert this dictionary list below into a dictionary

data=[
    {
        'code':'matata',
        'commandes':[
            {
                'date':'12-10-22',
                'content':[
                    {
                        'article':'Article1',
                        'designation':'Designe1',
                        'quantity':5
                    }
                ]
            }
        ]
    }
]

And I would like to have this result, just the starting brackets that we change to {..}

data={
{
    'code':'matata',
    'commandes':[
        {
            'date':'12-10-22',
            'content':[
                {
                    'article':'Article1',
                    'designation':'Designe1',
                    'quantity':5
                }
            ]
        }
    ]
  }
}

CodePudding user response:

Rather, You can use the 0th index of list and return dictionary.

data = data[0]
print(data)

#output
data ={
    'code':'matata',
    'commandes':[
        {
            'date':'12-10-22',
            'content':[
                {
                    'article':'Article1',
                    'designation':'Designe1',
                    'quantity':5
                }
            ]
        }
    ]
  }

(UPDATE 1)If you have multiple proucts:

for product in data:
   print(product)

(UPDATE 2) To print comma:

for product in data:
   print(product, end =",")
  • Related