2013-04-02 58 views
-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'}} 

所以我不明白爲什麼我不能訪問這些項目。

回答

3

你的問題只是你如何試圖訪問的項目:

for i in myInstances: 
    # i iterates over the KEYS in myInstances 
    print i.name.rjust(25), i.myid 

這種嘗試,在myInstances每個關鍵,打印i.name.rjust(25)等。你想要的是訪問值給定鍵(並使用正確的Python語法訪問字典元素):

for i in myInstances: 
    # i iterates over the KEYS in myInstances 
    print myInstances[i]["name"].rjust(25), myInstances[i]["myid"] 

或者,如果你不需要按鍵所有,只是遍歷擺在首位的值:

for i in myInstances.values(): 
    # i iterates over the VALUES in myInstances 
    print i["name"].rjust(25), i["myid"] 

或者最後,每個請求的,如果你真的想一次鍵和值迭代:

for k, v in myInstances.iteritems(): 
    print k, v["name"].rjust(25), v["myid"] 
+0

的感謝!有沒有像'for k,v in myInstances'? – cwd

+1

@cwd當然;這是'iteritems'方法(編輯到我的答案只爲你:-))。 –