[英]Iterate through a list of list in python
我正在從API中讀取json中的以下嵌套字典
{
"result": [{
"short_description": "I am getting bluescreen error",
"sys_id": "39b5f8c2376ede007520021a54990e5c",
"opened_at": "2016-04-04 05:19:53",
"number":"INC0258523"
},
{
"short_description": "laptop crashed with a blue screen",
"sys_id": "da0095380f43d200a4f941fce1050eeb",
"opened_at":"2016-04-25 06:33:52",
"number":"INC0259067"
},
{
"short_description": "Laptop not booting",
"sys_id": "ecf9c9b00f43d200a4f941fce1050e17",
"opened_at": "2016-04-25 06:07:16",
"number": "INC0259061"
}]
}
我需要根據兩個日期和兩個日期來過濾數據。 opened_at
是包含日期信息的值。
到目前為止,我的嘗試如下
url = "http://ip:port/api"
response = urllib.urlopen(url)
data = json.loads(response.read())
print type(data)
pattern = 'opened_at'
element = '2016-04-25 06:33:19'
with open('D:/Output.csv', 'wb') as f:
w = csv.DictWriter(f, data['result'][0].keys())
w.writeheader()
print type(data['result'])
for key in data['result']:
for v, val in data['result'].items():
if v == pattern and val == element:
w.writerow(v)
我在運行代碼時遇到以下錯誤
AttributeError: 'list' object has no attribute 'items'
我知道data ['result']的類型是列表。任何幫助將不勝感激。 謝謝!
data['result']
是字典的列表,您應該像下面這樣迭代它:
for d in data['result']:
for k, v in d.items():
你需要這個
import json
al = """
{
"result": [{
"short_description": "I am getting bluescreen error",
"sys_id": "39b5f8c2376ede007520021a54990e5c",
"opened_at": "2016-04-04 05:19:53",
"number":"INC0258523"
},
{
"short_description": "laptop crashed with a blue screen",
"sys_id": "da0095380f43d200a4f941fce1050eeb",
"opened_at":"2016-04-25 06:33:52",
"number":"INC0259067"
},
{
"short_description": "Laptop not booting",
"sys_id": "ecf9c9b00f43d200a4f941fce1050e17",
"opened_at": "2016-04-25 06:07:16",
"number": "INC0259061"
}]
}
"""
myjson = json.loads(al)
for val in myjson['result']:
print val['opened_at']
for key, value in val.items():#change it to keys if required
實際上,“結果”是字典。 您可以通過在其上加上圓圈的“ {”和“}”來識別字典中的字典。 因此,這是詞典列表中的詞典!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.