创建一个字典列表boto AWS

时间:2014-07-10 16:41:06

标签: python amazon-web-services boto

我正在尝试创建所有警报属性及其值的列表。这就是我想要做的。

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 个答案:

答案 0 :(得分:2)

您正在向x填充相同字典对象的引用。 Python中的字典是可变的,它们可以就地更改,因此尽管您在每次迭代时更改字典(从而查看打印的相应结果),但这也会改变列表中的所有“其他字典”。

试试这个:

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)

答案 1 :(得分:0)

每次都使用相同的dict对象,因此x只是对同一个对象的一堆引用。怎么样:

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