AWS

2014-07-10 7 views
0

나는 모든 알람 속성과 그 값의 목록을 만들기 위해 노력하고 BOTO 사전의 목록을 만들 수 있습니다. 이것이 내가하려는 일이다.AWS

import json 
import boto.ec2.cloudwatch 

conn = boto.ec2.cloudwatch.connect_to_region('ap-southeast-1') 
alarms = conn.describe_alarms() 

single_dict = {} 

whitelist = ["name", "metric", "namespace", "statistic", "comparison", "threshold", "period", "evaluation_periods", "unit", "description", "dimensions", "alarm_actions", "insufficient_data_actions", "ok_actions"] 
x = [] 
for alarm in alarms: 
    for attr in whitelist: 
     single_dict[attr] = getattr(alarm, attr) 

    print single_dict 
    x.append(single_dict) 
print x 

이 해결책은 효과가 없습니다. 항상 동일한 값을 포함하는 사전 목록을 얻습니다. 하지만 예를 들어 single_dict를 인쇄하려고하면 각 반복마다 올바른 값을 얻습니다. 왜 그럴까요?

답변

2

x에 대한 참조와 동일한 사전 객체을 채우고 있습니다. 파이썬의 사전은 각 반복에 사전을 변경 (및 인쇄 적절한 결과를 참조)이 또한 목록에서 "다른 사전"의 모든 변경 그래서 비록 그들은 자리에서 변경 될 수 있습니다, 변경할 수 있습니다.

이 시도 :

whitelist = ["name", "metric", "namespace", "statistic", "comparison", "threshold", "period", "evaluation_periods", "unit", "description", "dimensions", "alarm_actions", "insufficient_data_actions", "ok_actions"] 
x = [] 
for alarm in alarms: 
    single_dict = {} # new dictionary object each time 
    for attr in whitelist: 
     single_dict[attr] = getattr(alarm, attr) 

    print single_dict 
    x.append(single_dict) 
+0

이있어, 빠른 답장을 보내 주셔서 감사합니다 :) – hjelpmig

0
같은 DICT 개체마다 사용하고

때문에, x는 같은 일에 대한 참조 단지 무리입니다. 방법에 대해 :

x = [{attr: getattr(alarm, attr)} for alarm in alarms for attr in whitelist]