如何在python字典中获取键的值

2024-06-25 22:33:23 发布

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

我有这个python输出,它检索一个字典,如下所示。我想得到TopicArn的值,它位于NotificationConfiguration之内

这是我的输出看起来像

clusters的输出

{
    'Marker': 'string',
    'CacheClusters': [
        {
            'CacheClusterId': 'string',
            'ConfigurationEndpoint': {
                'Address': 'string',
                'Port': 123
            },
            'ClientDownloadLandingPage': 'string',,
            'PendingModifiedValues': {
                'NumCacheNodes': 123,
                'CacheNodeIdsToRemove': [
                    'string',
                ],
                'EngineVersion': 'string',
                'CacheNodeType': 'string',
                'AuthTokenStatus': 'SETTING'|'ROTATING'
            },
            'NotificationConfiguration': {
                'TopicArn': 'string',
                'TopicStatus': 'string'
            },        
            'ReplicationGroupId': 'string',
        },
    ]
}

这就是我所尝试的:

def get_ec_cache_Arn(region, clusters):
    ec_client = boto3.client('elasticache', region_name=region)

    count = 1

    for cluster in clusters['CacheClusters']:
        cluster_arn = cluster['NotificationConfiguration'][0]['TopicArn']

但这不起作用。没有输出。但是clusters有一个值我正在从其他函数传递。当我打印clusters时,它生成上面提到的字典。这意味着clusters不是空的

有人能帮我吗


Tags: clientstring字典portaddressmarkerregionclusters
3条回答

修改for循环。您已经将[0]放在那里,它将抛出KeyError,因为在python中,字典没有顺序,您不能对它们使用索引

for cluster in clusters['CacheClusters']:
        cluster_arn = cluster['NotificationConfiguration']['TopicArn']

这将提供所需的输出

   for cluster in clusters['CacheClusters']:
        cluster_arn = cluster['NotificationConfiguration']['TopicArn']

您的代码中有过多的[0]。您已尝试访问元素0,但“NotificationConfiguration”是字典而不是列表

我想分享一个访问字典元素的通用方法:

for key, value in clusters.items():
  assert clusters[key] == value, "access the value according to the key".

相关问题 更多 >