0

I have this python output that retrieves a dictionary like below. I want to get the value of TopicArn that falls inside NotificationConfiguration.

This is my output looks like.

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

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. But clusters has a value I am passing from some other function. When I print clusters it produces the above-mentiond dictionary. That means clusters is not empty.

Can someone help me?

2
  • 1
    There's nothing in the code fragment you posted that's even capable of producing any output, so it's not very clear what you're asking here. Commented Apr 22, 2020 at 9:32
  • Your code should actually raise a KeyError, so please edit your question with a PROPER minimal reproducible example and the full matching traceback. Also note that python has a very comprehe,sive tutorial, a full documentation, an interactive shell and a step debugger, so use all those features before posting here. Commented Apr 22, 2020 at 9:33

3 Answers 3

2

Modify your for loop. You've put [0] there which will throw KeyError because in python dictionaries are not ordered and you can't use indexing with them.

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

This gives desired output.

Sign up to request clarification or add additional context in comments.

Comments

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

You have an excessive [0] in your code. You've tried to acces element 0, but 'NotificationConfiguration' is a dictionary and not a list.

Comments

0

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". 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.