Create a list of names whose height is higher than 160 - 关于嵌套字典循环的解释
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
你能帮我找到解决办法吗?我正在学习 python,我知道骑自行车等,但令我烦恼的是嵌套字典。
不知何故我无法轻松访问它。
如果您还可以添加一些关于如何访问和循环嵌套字典的说明,我将不胜感激。谢谢
当你处理 dict 时,你可以利用 items() method 来循环它。
这里有一个关于如何做到这一点的明确代码:
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)
如果你觉得舒服,你可以使用一个衬垫以更 pythonic 的方式来完成它(感谢 ):
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)
输出:
['Anna', 'Dende']
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
你能帮我找到解决办法吗?我正在学习 python,我知道骑自行车等,但令我烦恼的是嵌套字典。 不知何故我无法轻松访问它。
如果您还可以添加一些关于如何访问和循环嵌套字典的说明,我将不胜感激。谢谢
当你处理 dict 时,你可以利用 items() method 来循环它。
这里有一个关于如何做到这一点的明确代码:
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)
如果你觉得舒服,你可以使用一个衬垫以更 pythonic 的方式来完成它(感谢
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)
输出:
['Anna', 'Dende']