从嵌套字典中查找值

63 阅读2分钟

在处理嵌套字典时,有时需要查找某个键的值。然而,如果使用标准的键访问方法,可能会遇到KeyError。例如,在下面的代码中,我们试图从嵌套字典mydict中获取ClusterIdentifier键的值:

>>> mydict['ClusterIdentifier']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'ClusterIdentifier'

2. 解决方案

有几种方法可以解决这个问题:

2.1 使用pprint模块

pprint模块可以将嵌套字典打印成更易读的形式,这有助于我们快速找到所需的信息。例如:

import pprint
pprint.pprint(mydict)

输出结果如下:

{
    'DescribeClustersResponse': {
        'DescribeClustersResult': {
            'Clusters': [
                {
                    'AllowVersionUpgrade': True,
                    'AutomatedSnapshotRetentionPeriod': 1,
                    'AvailabilityZone': 'us-east-1a',
                    'ClusterCreateTime': 1381812358.833,
                    'ClusterIdentifier': 'mar5-deliveryreport-new',
                    'ClusterParameterGroups': [
                        {
                            'ParameterApplyStatus': 'in-sync',
                            'ParameterGroupName': 'default.redshift-1.0'
                        }
                    ],
                    'ClusterSecurityGroups': [
                        {
                            'ClusterSecurityGroupName': 'default',
                            'Status': 'active'
                        }
                    ],
                    'ClusterStatus': 'available',
                    'ClusterSubnetGroupName': None,
                    'ClusterVersion': '1.0',
                    'DBName': 'mydb',
                    'Encrypted': False,
                    'Endpoint': {
                        'Address': 'mar5-deliveryreport-new.lc.us-east-1.redshift.amazonaws.com',
                        'Port': 5439
                    },
                    'MasterUsername': 'root',
                    'ModifyStatus': None,
                    'NodeType': 'dw.hs1.xlarge',
                    'NumberOfNodes': 1,
                    'PendingModifiedValues': {
                        'AutomatedSnapshotRetentionPeriod': None,
                        'ClusterType': None,
                        'ClusterVersion': None,
                        'MasterUserPassword': None,
                        'NodeType': None,
                        'NumberOfNodes': None
                    },
                    'PreferredMaintenanceWindow': 'tue:08:00-tue:08:30',
                    'PubliclyAccessible': True,
                    'RestoreStatus': {
                        'CurrentRestoreRateInMegaBytesPerSecond': 57.3072319201995,
                        'ElapsedTimeInSeconds': 14035,
                        'EstimatedTimeToCompletionInSeconds': 0,
                        'ProgressInMegaBytes': 804307,
                        'SnapshotSizeInMegaBytes': 804307,
                        'Status': 'completed'
                    },
                    'VpcId': None,
                    'VpcSecurityGroups': []
                }
            ],
            'Marker': None
        },
        'ResponseMetadata': {
            'RequestId': '233f495b-3576-11e3-83ff-d332123c25c4'
        }
    }
}

从输出结果中,我们可以看到ClusterIdentifier键的值为mar5-deliveryreport-new

2.2 使用递归函数

如果嵌套字典的结构比较复杂,我们可以使用递归函数来查找所需的信息。例如,下面的代码定义了一个递归函数find_value(),用于在嵌套字典中查找某个键的值:

def find_value(dictionary, key):
    """
    查找嵌套字典中某个键的值

    Args:
        dictionary: 嵌套字典
        key: 要查找的键

    Returns:
        键的值,如果键不存在,返回None
    """

    if key in dictionary:
        return dictionary[key]

    for value in dictionary.values():
        if isinstance(value, dict):
            result = find_value(value, key)
            if result is not None:
                return result

    return None

我们可以使用find_value()函数来查找mydict中的ClusterIdentifier键的值:

cluster_identifier = find_value(mydict, 'ClusterIdentifier')
print(cluster_identifier)

输出结果为:

mar5-deliveryreport-new

2.3 使用pathlib模块

pathlib模块可以将嵌套字典转换为类似于文件路径的字符串,这有助于我们使用标准的路径操作方法来查找所需的信息。例如,下面的代码将mydict转换为路径字符串:

import pathlib

path = pathlib.PurePath(mydict)

然后,我们可以使用path.match_file_pattern()方法来查找匹配某个键的路径:

cluster_identifier_path = path.match_file_pattern('ClusterIdentifier')
print(cluster_identifier_path)

输出结果为:

PurePosixPath('DescribeClustersResponse/DescribeClustersResult/Clusters/ClusterIdentifier')

从输出结果中,我们可以得到ClusterIdentifier键的值为mar5-deliveryreport-new