[英]Iterate through a list of list in python
I am reading the following nested dictionary in json from an API 我正在从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"
}]
}
I need to filter the data based on two from and two dates. 我需要根据两个日期和两个日期来过滤数据。
opened_at
is the value containing the date info. opened_at
是包含日期信息的值。
My attempt so far is as follows 到目前为止,我的尝试如下
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)
I get the below error on running the code 我在运行代码时遇到以下错误
AttributeError: 'list' object has no attribute 'items'
I know that the type of data['result'] is a list.Any help will be appreciated. 我知道data ['result']的类型是列表。任何帮助将不胜感激。 Thanks!
谢谢!
data['result']
is a list of dictionaries, you should iterate on it like follows: data['result']
是字典的列表,您应该像下面这样迭代它:
for d in data['result']:
for k, v in d.items():
you need this 你需要这个
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
Actually "Result" is a dictionnary. 实际上,“结果”是字典。 You can recognize a dictionnary in Python by the "{" and "}" it is circled with.
您可以通过在其上加上圆圈的“ {”和“}”来识别字典中的字典。 So here it is a dictionnary of a list of dictionnaries !
因此,这是词典列表中的词典!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.