【发布时间】:2020-01-24 18:43:35
【问题描述】:
我正在尝试从字典列表中创建一个包含特定键值的字典。我相信当我输入 chunkdata.extend(pythondict[0][1][2], chunkdata 时,我的代码不会使字典变平,chunkdata 将返回整个第一个第二和第三个字典,我想要像“名称”键这样的东西对在响应中返回的所有字典。
chunkdata = []
for chunk in chunklist:
url3 = "some URL"
headers = {'accept': 'application/json',
response = requests.request("GET", url3, headers=headers)
time.sleep(5)
print(response.text)
pythondict = json.loads(response.text)
print(pythondict)
chunkdata.extend(pythondict['name']['age']['date']
pythondict 输出
[{'data': {'name': 'jon', 'age': '30', 'date': '2020-01-05', 'time': '1', 'color': '蓝色'},{'数据':{'名称':'phil','年龄':'33','日期':'2020-01-05','时间':'1','颜色' : 'blue'}, {'data': {'name': 'ted', 'age': '25', 'date': '2020-01-05', 'time':'1', 'color ': '蓝色'}]
Traceback (most recent call last):
File line 84, in <module>
chunkdata.extend(pythondict['name']['age']['date']
TypeError: list indices must be integers or slices, not str
【问题讨论】:
-
print(pythondict)的输出是什么? -
print(pythondict) 输出是从 response.text 中的原始 json 转换而来的字典列表
-
如果我们能看到那些字典就好了...... >
-
['name']['age']['date']之一是列表而不是字典。除此之外,没有人能为您的问题提供更好的答案。
标签: python json python-3.x python-requests