2016-06-29 126 views
-2

dict類型的響應語法:如何訪問字典值?

{ 
    'StoppingInstances': [ 
     { 
      'InstanceId': 'string', 
      'CurrentState': { 
       'Code': 123, 
       'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' 
      }, 
      'PreviousState': { 
       'Code': 123, 
       'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' 
      } 
     }, 
    ] 
} 

現在,如果我需要檢查,如果在currentState是stopping怎麼辦呢?

print "Stopping instance Now",response['StoppingInstances'] 

for instance in response['StoppingInstances']: 
    if instance['CurrentState']['Name'] == "stopping": 
     print "Still Stooping" 

    if instance['CurrentState']['Name'] == "stopped": 
     print "Instance Stopped" 
print "Now Starting the instance" 
response_new = client.start_instances(InstanceIds=[instance_id]) 
for start_instance in response_new['StartingInstances']: 
    if start_instance['CurrentState']['Name'] == "running": 
     print "Instance is UP and running" 
    else: 
     print "Some Error occured!!" 
+0

只要看看你的數據。 'response ['StoppingInstances']'是一個列表(數組,在JSON中),你需要用一個整數索引它。 – jonrsharpe

回答

0

response['StoppingInstances']對象是字典的列表。你必須要麼環比那些或索引中的單個項目:

response['StoppingInstances'][0]['CurrentState']['Name'] == "stopping" 

如果你需要測試,如果任何這些對象是在stopping狀態,你可以使用any()功能:

any(o['CurrentState']['Name'] == "stopping" for o in response['StoppingInstances']) 

如果你需要測試每個實例,使用循環:

for instance in response['StoppingInstances']: 
    if instance['CurrentState']['Name'] == "stopping": 
+0

它是如何確定它是字典的列表? – DrugLORD

+0

@DrugLORD:仔細查看語法。你有一個'[...]'列表,包含一個'{...}'字典。密鑰的名稱也是一個提示;它是'StoppingInstances',*複數*,而不是'StoppingInstance',單數。 –

+0

哦好吧,我實際上試圖停止並開始一個一個的實例,我正在更新代碼,你可以看看 – DrugLORD

0

你的數據包含封閉歐特列表字典值,而不是簡單的嵌套字典,如你所想。您需要索引列表,然後通過鍵訪問嵌套字典值:

response['StoppingInstances'][0]['CurrentState']['Name'] 
#       ^

而在你if塊:

if response['StoppingInstances'][0]['CurrentState']['Name'] == "stopped": 
    print "Instance Stopped" 
+0

我怎麼知道更多關於字典? – DrugLORD

+0

@DrugLORD有很多好的在線教程,如[this one](http://www.python-course.eu/dictionaries.php),但你的第一個參考應該是[數據結構上的python文檔](https:/ /docs.python.org/2/tutorial/datastructures.html#dictionaries) –

+0

謝謝摩西,我已經更新了新的代碼,你可以看一下嗎? – DrugLORD