迭代嵌套字典以检查特定值是否都是数字字母

2024-09-30 14:19:44 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是我拥有的一个非常大的嵌套字典的子集:

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

Tags: nameinfononeidage字典liwatson
3条回答

使用isdigit

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):
    if height.isdigit():
        return height

for some_id, info in data.items():
    print("\nID:", some_id)
    print("Height:", person_height(info['Height']))

输出:

ID: 1
Height: 150

ID: 2
Height: 175

ID: 3
Height: 162

ID: 4
Height: None

您也可以使用list comprehension来执行此操作

def get_heights(data):
    return [int(person['Height'])
            if person['Height'].isdigit()
            else None
            for person in data.values()]

print(get_heights(data))

使用示例数据输出运行它:

[150, 175, 162, None]

因为您没有使用id,所以可以使用.values()而不是.items()。在代码中,您将参数命名为height,然后在函数体中引用data。这意味着你提供什么作为论据并不重要;代码之所以有效,是因为它引用的是全局定义的变量,而该变量恰好具有相同的名称

我还将高度转换为整数,即使您没有特别要求

实际上,您的代码很好,但是return将立即中断循环并仅返回第一个结果,因此只需将return转换为print()即可

另一种方法是先将结果保存到列表中,然后再读取:

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(data):
    height_list = []
    for some_id, info in data.items():
        if info['Height'].isnumeric():
            height_list.append(info['Height'])
        else:
            height_list.append(None)
    return height_list

for height in person_height(data):
    print(height)

输出:

150
175
162
None

相关问题 更多 >