繁体   English   中英

从键/值对中获取价值

[英]get value out of the key/value pair

对于那里的某些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'
>>>

它们是函数,可以这样称呼它们:

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

要获取确切的元数据:

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

编辑:

正如@Anand S Kumar指出的那样,如果有多个快照,您将不得不循环循环遍历它们,如他所演示的那样。

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

print rs.values()

rs.keys相同,它也是一个函数,将其rs.keys()

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

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

或就像@CasualDemon在他的答案中给出的那样,如果您只想要第一个快照的VolumeId ,则可以-

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

如果我没有记错的话,您想要获得的是与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语法

暂无
暂无

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

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