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

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']

Leave a Comment