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

Create a list of names whose height is higher than 160 – Explanation on nested dicts cycling

patients_dict = {"Anna": {'age':16, 'height':165, 'weight':65},
                 "Barbara" : {'age':100, 'height':120, 'weight':40},
                  "Carlo" : {'age':36, 'height':150, 'weight':60},
                 "Dende" : {'age':27, 'height':183, 'weight':83}}

# Create a list of names whose height is higher than 160

Can you help me find a solution? I’m learning python, I know cycling etc but what is buggin me is the nested dictionary.
Somehow I can’t access it easily.

I would really appreciate it if you can add also a little explanation on how to access and cycle trough nested dictionary. Thanks.

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

>Solution :

As you are dealing with dict, you can leverage the items() method to loop through it.

Here is an explicit code on how to do so:

patients_dict = {"Anna": {'age':16, 'height':165, 'weight':65},
                 "Barbara" : {'age':100, 'height':120, 'weight':40},
                  "Carlo" : {'age':36, 'height':150, 'weight':60},
                 "Dende" : {'age':27, 'height':183, 'weight':83}}

tall_patients = []

for patient, infos in patients_dict.items():
    # Values for the first iteration:
    # patient -> Anna
    # infos -> {'age':16, 'height':165, 'weight':65}
    for info, value in infos.items():
        # Values for the first iteration:
        # info -> age
        # value -> 16
        if info == "height":
            if value > 160:
                tall_patients.append(patient)

print(tall_patients)

And if you feel comfortable, you could use a one liner to do it in a more pythonic way (thanks to @Matthias):

patients_dict = {"Anna": {'age':16, 'height':165, 'weight':65},
                 "Barbara" : {'age':100, 'height':120, 'weight':40},
                  "Carlo" : {'age':36, 'height':150, 'weight':60},
                 "Dende" : {'age':27, 'height':183, 'weight':83}}
tall_patients = [name for name, data in patients_dict.items() if data['height'] > 160]
print(tall_patients)

Outputs:
['Anna', 'Dende']

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