从键/值对中获取值

时间:2015-08-19 20:19:28

标签: python python-2.7 python-3.x boto boto3

对于某些python专业人士来说,这可能是一个非常微不足道的问题,但我正在使用boto3来获取一些快照信息....我在下面做了以后得到了...我的问题是我如何得到只是“VolumeId”,我认为这是一个关键的值输出,我可以使用一些值rs.value来获得,但我没有得到所需的输出......

>>> import boto3
>>> client = boto3.client('ec2')
>>> rs = client.describe_snapshots(SnapshotIds=['snap-656f5566'])
>>> print rs
{'ResponseMetadata': {'HTTPStatusCode': 200, 'RequestId': '6f99cc31-f586-48cf-b9bd-f5ca48a536fe'}, u'Snapshots': [{u'Description': 'Created by CreateImage(i-bbe81dc1) for ami-28ne0f44 from vol-72e14126', u'Encrypted': False, u'VolumeId': 'vol-41e14536', u'State': 'completed', u'VolumeSize': 30, u'Progress': '100%', u'StartTime': datetime.datetime(2012, 10, 7, 14, 33, 16, tzinfo=tzlocal()), u'SnapshotId': 'snap-658f5566', u'OwnerId': '0111233286342'}]}
>>>
>>>
>>> dir(rs)
['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
>>>
>>> print rs.keys
<built-in method keys of dict object at 0x1e76a60>
>>>
>>> print rs.values
<built-in method values of dict object at 0x1e76a60>
>>>

修复后出错

>>> print rs.keys()
['ResponseMetadata', u'Snapshots']
>>> print(rs['ResponseMetadata']['Snapshots'][0]['VolumeId'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'Snapshots'
>>>

3 个答案:

答案 0 :(得分:7)

它们是函数,称之为:

print rs.keys()
print rs.values()

获取确切的元数据:

print(rs['Snapshots'][0]['VolumeId'])

编辑:

正如@Anand S Kumar指出的那样,如果有一个以上的快照,你将不得不在循环中迭代它们,正如他所展示的那样。

答案 1 :(得分:3)

rs.values是一个函数,你需要调用它 -

print rs.values()

同样适用于rs.keys,它也是一个函数,称之为rs.keys()

但是如果您的情况只是获得VolumeId,您可以在首先获取快照列表之后使用subscript直接访问它,然后对其进行迭代并为每个快照获取volumeId -

snapshots = rs['Snapshots']
for snapshot in snapshots:
    print snapshot['VolumeId']

或者正如@CasualDemon在答案中给出的那样,如果您只想要VolumeId作为第一个快照,那么您可以这样做 -

print rs['Snapshots'][0]['VolumeId']

答案 2 :(得分:0)

如果我没弄错,你想得到的是与u'VolumeId相关的价值, 那就是'vol-41e14536'(如果您有多个快照,还有更多值)。

rs是一个字典,其u'Snapshot'键与字典列表(实际上只有一个字典)相关联,并且这些字典包含一个键u'VolumeId',其中包含您想要的相关值。

{ ....                   u'Snapshot' : [                                 {...                        u'VolumeId': 'vol-41e14536' ...}  ] ... }
^Beginning of dictionary ^key          ^Value(list of dictionaries)      ^firstElement(a dictionary) ^The key you are looking for and its value

你能做的是

snapshots = rs[u'Snapshots']
volumeIds = []
for snapshotDict in snapshots :
    volumeIds.append(snapshotDict[u'VolumeId'])
print(volumeIds)

假设python3语法