Skip to content
Advertisement

Python: cannot get a value from nested dict

I am trying to loop over array of dicts and create a new dict using a for loop:

data

src_roles = [{
    "rol1": {
        "identity": 169309,
        "labels": [
            "Role"
        ],
        "properties": {
        "cs_id": "AB778C",
        "name": "CMO",
        "critical_role": True
          }
    }
}]

for loop:

src_roles_dict = { 
    role['rol1']['cs_id']: role for role in src_roles if role['rol1'].get('cs_id')
}

And when I print src_roles_dict, I get an empty dict {}

Is there something I am missing? Sorry, coming from golang background.

Advertisement

Answer

src_roles = [{
    "rol1": {
        "identity": 169309,
        "labels": [
            "Role"
        ],
        "properties": {
        "cs_id": "AB778C",
        "name": "CMO",
        "critical_role": True
          }
    }
}]

src_roles_dict = {
    role['rol1']["properties"]['cs_id']: role for role in src_roles if role["rol1"]["properties"].get("cs_id")
}

print(src_roles_dict)

Output

{'AB778C': {'rol1': {'identity': 169309, 'labels': ['Role'], 'properties': {'cs_id': 'AB778C', 'name': 'CMO', 'critical_role': True}}}}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement