python无法读取字典中的键

时间:2019-03-19 19:21:23

标签: python dictionary

我有来自AWS的这句话:

https://pastebin.com/pG02WANu

我正在尝试获取名称密钥:

HealthChecks-> HealthCheckConfig-> AlarmIdentifier->名称

但是似乎python在HealthCheckConfig处停止了

for alarm in alarms['HealthChecks']:
    print('Alarm: %s' % alarm )
    if unicode('AlarmIdentifier') in alarm['HealthCheckConfig']:
        print('Alarm Name: %s' % alarm['AlarmIdentifier'] )

我得到:

Alarm: {u'HealthCheckConfig': {u'InsufficientDataHealthStatus': '... u'MetricName': 'HTTPCode_Target_5XX_Count'}}

    Traceback (most recent call last):
  File "lambda_function.py", line 283, in <module>
    main()
  File "lambda_function.py", line 279, in main
    lambda_handler('start', 'test')
  File "lambda_function.py", line 263, in lambda_handler
    freeSWITCH.setHC(fsNode + ' CPU Health', aws_creds, 0)
  File "/home/admin/scripts/myscript/myscript.py", line 81, in setHC
    print('Alarm Name: %s' % alarm['AlarmIdentifier'] )
KeyError: 'AlarmIdentifier'

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

这是行得通的,@ PRMoureu指出了我的错误...我想我今天来已经太久了。

alarms = client.list_health_checks(MaxItems='2')
print('alarms: %s' % alarms)
for alarm in alarms['HealthChecks']:
    print('Alarm: %s\n==============================' % alarm )
    if unicode('AlarmIdentifier') in alarm['HealthCheckConfig']:
        print('FOUND')
        print('Alarm Name: %s' % alarm['HealthCheckConfig']['AlarmIdentifier']['Name'] )