Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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}}}}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading