简体   繁体   English

处理python字典中的缺失键

[英]Handle missing keys in python dictionary

I'm building a list of EC2 instances in Amazon. 我正在构建Amazon中的EC2实例列表。 And I am testing for the existence of keys called PrivateIpAddress and PublicIpAddress in a dictionary. 我正在测试字典中是否存在称为PrivateIpAddress和PublicIpAddress的键。 In some cases neither key exists and I get an exception: 在某些情况下,这两个键都不存在,并且出现异常:

-------------------------------------
Instance ID: i-86533615
Type: m4.xlarge
State: stopped
Private IP: 10.1.233.18
Traceback (most recent call last):
  File ".\aws_ec2_list_instances.py", line 43, in <module>
    print(Fore.CYAN + "{0}: {1}".format(key, instance[key]))
KeyError: 'Public IP'

My code says: 我的代码说:

for instance in reservation["Instances"]:
if 'PrivateIpAddress' in instance and 'PublicIpAddress' in instance:
    ... do stuff...
elif 'PrivateIpAddress' in instance:
else:
    ...do stuff..

But the last else doesn't catch the problem of an instance not having either a public ip address or a private ip address. 但是最后一个并没有解决实例既没有公共IP地址也没有私有IP地址的问题。

Here is the full code in python: list ec2 instances 这是python中的完整代码: 列出ec2实例

for instance in reservation.get("Instances", []):
    private_ip_address = instance.get("PrivateIpAddress" , None)
    public_ip_address = instance.get("PublicIpAddress" , None)
    if  private_ip_address and public_ip_address:
    ... do stuff...
    elif private_ip_address:
       ...do stuff.. 
    else:
       ...do stuff..

Try this one 试试这个

I see a fundamental problem in your logic. 我认为您的逻辑存在一个基本问题。 You're looping through all the instances and building up maps for each of them in ec2info . 您正在遍历所有实例,并在ec2info中为每个实例建立映射。 But each time through the loop, when processing a particular instance, you're looping over all the data in ec2info , including the data added by previous iterations of the loop. 但是每次循环时,在处理特定实例时,您都要循环遍历ec2info中的所有数据,包括由循环的先前迭代添加的数据。 I bet you don't really want to do this. 我敢打赌,您真的不想这样做。 I bet you really want to display the attributes for just the instance you're working on. 我敢打赌,您真的只想显示您正在处理的实例的属性。

Here's the key to your problem: 这是解决问题的关键:

attributes = ['Instance ID', 'Type',
    'State', 'Private IP', 'Launch Time' ]
for instance_id, instance in ec2info.items():

So here, you're iterating over all the maps in ec2info , and yet you're applying a set of 'attributes' that are specific to the one instance you're currently processing. 因此,在这里,您要遍历ec2info中的所有地图,但是您要应用一组特定于您当前正在处理的实例的“属性”。 Since in general, per your own code, not all of the maps in ec2info will have all of the same keys, you're getting the error you're getting. 由于通常来说,按照您自己的代码,并不是ec2info中的所有映射都具有所有相同的键,因此您会遇到错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM