python - 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]
解决方案
将您的代码更改为:
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 代码更简洁。但是,我更喜欢更容易阅读的罗嗦风格。
另请注意,此代码检查密钥是否存在,以便代码不会因丢失数据而堆栈转储。
推荐阅读
- django - 是否可以在没有 kwargs 的情况下在 django 中定义 success_url
- c# - 事件和代表的对立面?
- sql - 将名称之间的链接列表合并为一列
- oauth - Microsoft Graph 控制台应用程序 - OAuth
- python - 在 Django Rest Framework URL 中通过唯一 ID 而非 PK 获取详细信息
- python - Python3:有没有办法像在 python2 中一样使用 telnetlib,没有 ascii 编码和 b 前缀?
- powershell - 当证书的现有指纹与站点匹配时,我想导入 SSL 证书
- mysql - 如何“复制”特定表中的行(同时自动分配新 ID)?
- linux - 内核 4.x 的 PACKET_MMAP 等价物是什么
- javascript - 即使在暂停时,如何让日期计数器停止在后台运行?任何和所有的帮助表示赞赏