Home > Blockchain >  Python: cannot get a value from nested dict
Python: cannot get a value from nested dict

Time:04-11

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.

CodePudding user response:

cs_id is in the properties dict. Better code formatting would make this more obvious:

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

Try this:

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

Alternatively, I find the assignment expression nice for things like this:

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

CodePudding user response:

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}}}}
  • Related