![](/img/trans.png)
[英]How to pull out value from Key:Value Pair with Databricks Notebook
[英]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.