RaptorPete
RaptorPete

Reputation: 159

How can I append values from a JSON dictionary to a new list?

I have a .json file of all of my AWS target groups. This was created using aws elbv2 describe-target-groups. I want to extract every TargetGroupArn from this file and store it into a Python list.

With my current code, I get no output. I can confirm that the dictionary has data in it, but nothing is being appended to the list that I'm trying to create.

import json
from pprint import pprint

with open('target_groups.json') as f:
    data = json.load(f)

items = data['TargetGroups']
arn_list = []
for key, val in data.items():
    if key == 'TargetGroupArn':
        arn_list.append(val)

print(arn_list)

Expected results would be for arn_list to print out looking like this:

[arn:aws:elb:xxxxxxx:targetgroup1, arn:aws:elb:xxxxxxx:targetgroup2, arn:aws:elb:xxxxxxx:targetgroup3]

Upvotes: 0

Views: 57

Answers (2)

Arootin Aghazaryan
Arootin Aghazaryan

Reputation: 848

it would be better if you could post the file you are trying to get data from, but this part:

for key, val in data.items():
if key == 'TargetGroupArn':
    arn_list.append(val)

need to be changed to:

for key, val in items.items():
if key == 'TargetGroupArn':
    arn_list.append(val)

you get data from 'data' and add it to items, but you never actually used it. give it a shot.

Upvotes: 1

John Hanley
John Hanley

Reputation: 81336

Change your code to this:

import json
from pprint import pprint

with open('target_groups.json') as f:
    data = json.load(f)

arn_list = []

if 'TargetGroups' in data:
    items = data['TargetGroups']

    for item in items:
        if 'TargetGroupArn' in item:
            arn_list.append(item['TargetGroupArn'])

    print(arn_list)
else:
    print('No data')

There are many ways to make this python code more concise. However, I prefer a more wordy style that easier to read.

Also note that this code checks that keys exist so that the code will not stackdump for missing data.

Upvotes: 1

Related Questions