-1
我試圖使用python和boto從Amazon EC2打印實例和IP的列表。如何在python中使用dict與boto和amazon ec2構建多維數組?
我習慣於PHP的漂亮的多維數組和類似的JSON語法,但我在python中遇到了很多麻煩。我嘗試使用自動授權,如What's the best way to initialize a dict of dicts in Python?中提到的,但我沒有運氣與訪問對象。
這裏是我的代碼:
import sys
import os
import boto
import string
import urllib2
from pprint import pprint
from inspect import getmembers
from datetime import datetime
class AutoVivification(dict):
"""Implementation of perl's autovivification feature."""
def __getitem__(self, item):
try:
return dict.__getitem__(self, item)
except KeyError:
value = self[item] = type(self)()
return value
conn = boto.connect_ec2_endpoint(ec2_url, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)
tags = conn.get_all_tags()
myInstances = AutoVivification()
for tag in tags:
if (tag.res_type == 'instance' and tag.name == 'Name'):
if(tag.res_id):
myInstances[tag.res_id]['myid'] = tag.res_id
myInstances[tag.res_id]['name'] = tag.value
addrs = conn.get_all_addresses()
for a in addrs:
if(a.instance_id):
myInstances[a.instance_id]['ip'] = a.public_ip
pprint(myInstances)
for i in myInstances:
print i.name.rjust(25), i.myid
如果我做pprint(myInstances)
話,我能看到,我已創建多維字典,但我無法與i.myid
訪問與子陣 - 我得到類似的錯誤:
AttributeError: 'unicode' object has no attribute 'myid'
AttributeError: 'unicode' object has no attribute 'name'
做pprint(myInstances)
給了我這樣的:
{u'i-08148364': {'myid': u'i-18243322', 'name': u'nagios', 'ip': u'1.2.3.4'}}
所以我不明白爲什麼我不能訪問這些項目。
的感謝!有沒有像'for k,v in myInstances'? – cwd
@cwd當然;這是'iteritems'方法(編輯到我的答案只爲你:-))。 –