首页 > 解决方案 > 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]

标签: python

解决方案


将您的代码更改为:

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

有很多方法可以让这个 python 代码更简洁。但是,我更喜欢更容易阅读的罗嗦风格。

另请注意,此代码检查密钥是否存在,以便代码不会因丢失数据而堆栈转储。


推荐阅读