[英]python nested lists/dictionaries and popping values
事先道歉,這是一個新手問題。 我剛剛開始編寫python,並且我一直對嵌套字典/列表中的彈出值感到困惑,所以我感謝任何幫助!
我有這個示例json數據:
{ "scans": [
{ "status": "completed", "starttime": "20150803T000000", "id":533},
{ "status": "completed", "starttime": "20150803T000000", "id":539}
] }
我想從“掃描”鍵中彈出“id”。
def listscans():
response = requests.get(scansurl + "scans", headers=headers, verify=False)
json_data = json.loads(response.text)
print json.dumps(json_data['scans']['id'], indent=2)
似乎沒有工作,因為嵌套的鍵/值在列表中。 即
>>> print json.dumps(json_data['scans']['id'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str
任何人都可以指出我正確的方向讓這個工作? 我的長期目標是創建一個for循環,將所有id放入另一個字典或列表,我可以用於另一個函數。
json_data['scans']
返回一個json_data['scans']
列表,你試圖使用str ie []["id"]
索引列表,由於顯而易見的原因失敗,所以你需要使用索引來獲取每個子元素:
print json_data['scans'][0]['id'] # -> first dict
print json_data['scans'][1]['id'] # -> second dict
或者看到所有id迭代在使用json_data["scans"]
返回的json_data["scans"]
列表上:
for dct in json_data["scans"]:
print(dct["id"])
要保存附加到列表:
all_ids = []
for dct in json_data["scans"]:
all_ids.append(dct["id"])
或使用列表comp:
all_ids = [dct["id"] for dct in json_data["scans"]]
如果密鑰id
可能不在每個字典in
,請在訪問之前使用in
進行檢查:
all_ids = [dct["id"] for dct in json_data["scans"] if "id" in dct]
在這里,您如何迭代項目並提取所有ID:
json_data = ...
ids = []
for scan in json_data['scans']:
id = scan.pop('id')
# you can use get instead of pop
# then your initial data would not be changed,
# but you'll still have the ids
# id = scan.get('id')
ids.append();
這種方法也有效:
ids = [item.pop('id') for item in json_data['scans']]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.