简体   繁体   English

如何在python中使用dict使用boto和Amazon EC2构建多维数组?

[英]How can I use a dict in python to build a multi-dimension array with boto and amazon ec2?

I'm attempting to use python and boto to print a list of instances and IPs from Amazon EC2. 我正在尝试使用python和boto从Amazon EC2打印实例和IP的列表。

I'm used to PHP's nice multidimensional arrays and the similar JSON syntax but I'm having a lot of trouble in python. 我已经习惯了PHP的漂亮多维数组和类似的JSON语法,但是在python中遇到了很多麻烦。 I tried using AutoVivification as mentioned in What's the best way to initialize a dict of dicts in Python? 我尝试使用“ 初始化Python的字典的最佳方法什么”中提到的AutoVivification but am not having luck with access objects in it. 但运气不佳,其中没有访问对象。

Here is my code: 这是我的代码:

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

If I do pprint( myInstances ) then I am able to see the multidimensional dict that I have created, but i am not able to access the sub-arrays with i.myid - I get errors like: 如果我执行pprint( myInstances )那么我可以看到自己创建的多维字典,但是我无法使用i.myid访问子数组-我得到如下错误:

AttributeError: 'unicode' object has no attribute 'myid'
AttributeError: 'unicode' object has no attribute 'name'

Doing pprint( myInstances) gives me something like: pprint( myInstances)给我类似的东西:

{u'i-08148364': {'myid': u'i-18243322', 'name': u'nagios', 'ip': u'1.2.3.4'}}

so I don't understand why I can't access these items. 所以我不明白为什么我无法访问这些项目。

Your problem is just in how you're trying to access the items: 您的问题仅在于您尝试访问项目的方式:

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

This attempts, for each key in myInstances , to print i.name.rjust(25) and so on. 对于myInstances每个 ,这将尝试打印i.name.rjust(25)等。 What you want is to access the value of the given keys (and to use the right Python syntax for accessing dictionary elements): 您想要的是访问给定键的 (并使用正确的Python语法访问字典元素):

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

Or if you don't need the keys at all, just iterate over the values in the first place: 或者,如果您根本不需要键,则只需首先迭代值即可:

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

Or finally, per request, if you really want to iterate over keys and values at once: 或者最后,根据您的请求,如果您真的想一次遍历键和值:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM