下面是我拥有的一个非常大的嵌套字典的子集:
{
'1': {'Name': 'Katherine Watson',
'Age': '1',
'Height': '150'},
'2': {'Name': 'Emilia Li',
'Age': '56',
'Height': '175'},
'3': {'Name': 'Dorothy Johnson',
'Age': '29',
'Height': '162'},
'4': {'Name': 'Alexandar Knight',
'Age': '14',
'Height': '164r'}
}
我很难理解如何编写一个函数来遍历特定的键('Height'),如果该键全部是数字或没有数字,则返回相应的值。 例如,ID为“1”的字典的高度应返回“150”。但是ID为“4”的字典应该为高度返回None
下面是我编写的代码,但它只返回“150”,而不是遍历所有ID并返回“150”“175”“162”“None”
data = {
'1': {'Name': 'Katherine Watson',
'Age': '1',
'Height': '150'},
'2': {'Name': 'Emilia Li',
'Age': '56',
'Height': '175'},
'3': {'Name': 'Dorothy Johnson',
'Age': '29',
'Height': '162'},
'4': {'Name': 'Alexandar Knight',
'Age': '14',
'Height': '164r'}
}
def person_height(height):
for some_id, info in data.items():
if info['Height'].isnumeric():
return info['Height']
else:
return None
使用
isdigit
输出:
您也可以使用list comprehension来执行此操作
使用示例数据输出运行它:
因为您没有使用id,所以可以使用
.values()
而不是.items()
。在代码中,您将参数命名为height
,然后在函数体中引用data
。这意味着你提供什么作为论据并不重要;代码之所以有效,是因为它引用的是全局定义的变量,而该变量恰好具有相同的名称我还将高度转换为整数,即使您没有特别要求
实际上,您的代码很好,但是
return
将立即中断循环并仅返回第一个结果,因此只需将return
转换为print()
即可另一种方法是先将结果保存到列表中,然后再读取:
输出:
相关问题 更多 >
编程相关推荐