Thursday, 20 August 2020

How to extract values from list of dictionary and added to list

How to extract values from list of dictionary and added to list

Data set is below. Here 'name' has to extract from the dictionary and append to the list

    a =  [
    {
        "id": "1",
        "Area": [
          {
            "id": "2",
            "name": "ABC"
          },
          {
            "id": "23",
            "name": "DEF"
          }],
    },{
      "id": "2",
        "Area": [
          {
            "id": "2",
            "name": "AB"
          },
          {
            "id": "23",
            "name": "CD"
          }]
      }
]

Expected out is below

   [{
    "id": "1",
    "Area": ["ABC","DEF"]
},{
       "id": "2",
    "Area": ["AB","CD"] 

  }]

Psuedo code

result = []
temp = {}
for i in a:
    for k,l in i.items():
        temp['id'] = k['id']
        temp['Area'] = k['Area']['name']
        result.append(temp)

        


from How to extract values from list of dictionary and added to list

No comments:

Post a Comment