Skip to content
Advertisement

How to iterate through a nested list of dictionaries in Python

I have a bit complicated json response from a server, below is my json:

    services = [{"Mobile": [{"name": "CompanyA", id: 0, address: "XYZ"},  
    {"name": CompanyB, id: 1, address: "QWE"},  
    {"name": CompanyC, id: 2, address: "TYU"}]  
    },
    {"Computer": [{"name": "CompanyD", id: 3, address: "PPP"},  
    {"name": CompanyD, id: 4, address: "UYU"},  
    {"name": CompanyE, id: 5, address: "NMB"}]  
    }]   

I need to construct new dictionary which only holds bellow data:

services = [{"Mobile": [{"name": "CompanyA"},{"name": "CompanyB"}, 
          {"name": "CompanyC"}]},
          {"Computer": [{"name": "CompanyD"},{"name": "CompanyD"},  
          {"name": "CompanyE"}]  
    }]  

in other words, delete id and address fields.

Advertisement

Answer

Iterating through each nested dictionary/list and deleting the unwanted keys,

for i in services:
    for j in i.values():
        for k in j:
            del k[id]
            del k["address"]
            
print(services)

Output:
[{'Mobile': [{'name': 'CompanyA'}, {'name': 'CompanyB'}, {'name': 'CompanyC'}]}, {'Computer': [{'name': 'CompanyD'}, {'name': 'CompanyD'}, {'name': 'CompanyE'}]}]
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement