简体   繁体   English

如何获取 python 字典中键的值

[英]How to get the value of a key in python dictionary

I have this python output that retrieves a dictionary like below.我有这个python output 可以检索如下字典。 I want to get the value of TopicArn that falls inside NotificationConfiguration .我想获取属于NotificationConfigurationTopicArn的值。

This is my output looks like.这是我的 output 的样子。

output of clusters clusters的 output

{
    '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',
        },
    ]
}

This is what I tried:这是我尝试过的:

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

But this doesn't work.但这不起作用。 gives no output.没有给出 output。 But clusters has a value I am passing from some other function.但是clusters有一个值,我从其他一些 function 传递过来。 When I print clusters it produces the above-mentiond dictionary.当我打印clusters时,它会生成上面提到的字典。 That means clusters is not empty.这意味着clusters不是空的。

Can someone help me?有人能帮我吗?

Modify your for loop.修改你的for循环。 You've put [0] there which will throw KeyError because in python dictionaries are not ordered and you can't use indexing with them.你把[0]放在那里会抛出KeyError因为在 python 字典没有排序,你不能对它们使用索引。

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

This gives desired output.这给出了所需的 output。

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

You have an excessive [0] in your code.您的代码中有过多的[0] You've tried to acces element 0 , but 'NotificationConfiguration' is a dictionary and not a list.您已尝试访问元素0 ,但 'NotificationConfiguration' 是字典而不是列表。

I'd like to share a general method to access dictionary elements:我想分享一个访问字典元素的通用方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM