Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从json打印值并忽略键_Python_Python 3.x - Fatal编程技术网

Python 从json打印值并忽略键

Python 从json打印值并忽略键,python,python-3.x,Python,Python 3.x,我正在从aws获取一个服务器列表并打印它们,但是有时我会得到一些缺少的密钥: >>> servers=ec2_client.describe_instances() >>> for r in servers['Reservations']: ... for i in r['Instances']: ... print(i['InstanceId'], i['PrivateIpAddress'], i['PublicIpAddress']

我正在从aws获取一个服务器列表并打印它们,但是有时我会得到一些缺少的密钥:

>>> servers=ec2_client.describe_instances()
>>> for r in servers['Reservations']:
...     for i in r['Instances']:
...         print(i['InstanceId'], i['PrivateIpAddress'], i['PublicIpAddress'])
...
i-x x.y.z.p x.y.z.w
i-y x.y.z.p x.y.z.w
i-t x.y.z.p x.y.z.w
i-r x.y.z.p x.y.z.w
i-e x.y.z.p x.y.z.w
i-s x.y.z.p x.y.z.w
i-e x.y.z.p x.y.z.w
i-r x.y.z.p x.y.z.w
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
KeyError: 'PublicIpAddress'
>>servers=ec2\u client.description\u instances()
>>>对于服务器['Reservations']中的r:
...     对于r['Instances']中的i:
...         打印(i['InstanceId']、i['PrivateIpAddress']、i['PublicIpAddress'])
...
i-x x.y.z.p x.y.z.w
i-y x.y.z.p x.y.z.w
i-t x.y.z.p x.y.z.w
i-r x.y.z.p x.y.z.w
i-e x.y.z.p x.y.z.w
i-s x.y.z.p x.y.z.w
i-e x.y.z.p x.y.z.w
i-r x.y.z.p x.y.z.w
回溯(最近一次呼叫最后一次):
文件“”,第3行,在
KeyError:“PublicIpAddress”

如何在忽略缺少的键的情况下打印它(以一种很好的方式)?

如果python中缺少键,您可以为键提供默认值:

print(i.get('InstanceId', DEFAULT_ID), i.get('PrivateIpAddress', DEFAULT_PRIVATE), i.get('PublicIpAddress', DEFAULT_IP))
或者,如果要完全跳过缺少键的行,可以尝试:

for i in r['Instances']:
    try:
        print(i['InstanceId'], i['PrivateIpAddress'], i['PublicIpAddress'])
    except KeyError:
        pass

如果
i
是一个dict,那么可以执行
i.get(key,default)
以避免错误。在这种情况下,可能会将
默认值设置为
“[缺少IP地址]”
?是的,谢谢!