Python 值显示缺少所有内容的输出
我最近修改了一段代码,因为有人建议我用一种“更好”的方式来编写它。下一个代码块基本上获取所需的信息并在字典中创建它,还过滤某些标记为空的地方,并用“缺失”替换它们。这很有效Python 值显示缺少所有内容的输出,python,python-3.x,boto3,Python,Python 3.x,Boto3,我最近修改了一段代码,因为有人建议我用一种“更好”的方式来编写它。下一个代码块基本上获取所需的信息并在字典中创建它,还过滤某些标记为空的地方,并用“缺失”替换它们。这很有效 for instance in reservation['Instances']: ec2_info = {} ec2_info.update({'InstanceID':instance['InstanceId']}) ec2_
for instance in reservation['Instances']:
ec2_info = {}
ec2_info.update({'InstanceID':instance['InstanceId']})
ec2_info.update({'State':instance['State']['Name']})
ec2_info.update({'PrivateIpAddress':instance['PrivateIpAddress']})
ec2_info.update({'InstanceType':instance['InstanceType']})
for tag in instance['Tags']:
if tag['Key'] in 'Name':
ec2_info.update({'Name':tag['Value']})
for tag in instance['Tags']:
if tag['Key'] in 'environment':
ec2_info.update({'Environment':tag['Value']})
else:
ec2_info.setdefault('Environment','MISSING')
for tag in instance['Tags']:
if tag['Key'] in 'role':
ec2_info.update({'Role':tag['Value']})
else:
ec2_info.setdefault('Role','MISSING')
ec2_details.append(ec2_info)
return ec2_details
然后我将代码更改为:
Filters=[
{
'Name': 'tag:environment',
'Values': [env]
},
]
)
ec2_details = [
{
'InstanceID' : instance['InstanceId'],
'State' : instance['State']['Name'],
'PrivateIpAddress': instance['PrivateIpAddress'],
'InstanceType': instance['InstanceType'],
'Tags' : instance['Tags']
}
for reservation in data['Reservations'] for instance in reservation['Instances']
]
return ec2_details
通过明显删除if/else块,选择将这些代码进一步添加到输出部分:
ec2_info = get_instance_info(env)
for i in ec2_info:
if i in ec2_info:
name = [ tag['Value'] for tag in i['Tags'] if tag['Key'] == 'Name' ]
role = [ tag['Value'] if tag['Key'] == 'role' else 'Missing' for tag in i['Tags'] ]
environment = [ tag['Value'] if tag['Key'] == 'environment' else 'Missing' for tag in i['Tags'] ]
click.echo(f'{i["InstanceID"]: <30}{i["State"][0].upper():<5}{name[0]:<70}{i["PrivateIpAddress"]:<15}{role[0]:<30}{environment[0]:<50}{i["InstanceType"]}')
ec2\u info=get\u instance\u info(env)
对于ec2_信息中的i:
如果我在ec2_信息中:
name=[tag['Value']表示i['Tags']中的标记,如果tag['Key']=='name']
role=[tag['Value']如果i['Tags']]中的标记['Key']=='role'否则“缺少”]
环境=[tag['Value']如果i['Tags']]中的标记的标记['Key']=='environment'否则“缺少”]
click.echo(f'{i[“InstanceID]”):我有点知道为什么它在输出中显示“missing”。例如,键“role”出现在列表中,但随机放置。我特别使用角色[0]拾取列表中的第一项。我现在只需要弄清楚如何获得正确的结果。