Python “接收”';dict';对象不可调用";尝试使用openpyxl写入Excel时出错
我正在尝试使用openpyxl将从API GET请求提取的字典复制到excel;但是,代码正在生成“'dict'对象不可调用”错误。这是我的密码:Python “接收”';dict';对象不可调用";尝试使用openpyxl写入Excel时出错,python,json,dictionary,openpyxl,Python,Json,Dictionary,Openpyxl,我正在尝试使用openpyxl将从API GET请求提取的字典复制到excel;但是,代码正在生成“'dict'对象不可调用”错误。这是我的密码: import requests from pprint import pprint from openpyxl import Workbook r = requests.get('API URL & apikey') data = r.json() pprint(data) 此时,数据以子列表库形式返回,例如: {'results': [
import requests
from pprint import pprint
from openpyxl import Workbook
r = requests.get('API URL & apikey')
data = r.json()
pprint(data)
此时,数据以子列表库形式返回,例如:
{'results': [{'A':'alpha','B':'beta','C':'gamma'},
{'D':'delta','E':'epsilon','F':'zeta'}
...
{dictionary n}]
因为来自API的每个GET请求都会导致未知数量的嵌套库对象,所以我编写了代码来分离每个子库并将其重命名为自己的变量:
for n, val in enumerate(data['results']):
globals()["year%d"%n] = val
这会产生许多库,每个库都分配给自己的变量。都是。我通过运行以下命令来测试这一点:
all_variables = dir()
for name in all_variables:
if not name.startswith('__'):
myvalue = eval(name)
print(name, "is", type(myvalue), "and is equal to:")
print(myvalue)
print(" ")
其结果是:
year1 is <class 'dict'> and is equal to:
{'A':'alpha','B','beta','C','gamma'}
year2 is <class 'dict'> and is equal to:
{'D':'delta','E','epsilon','F':'zeta'}
...
yearN is...
由此产生的错误如下所示:
line 34, in <module> for key,values in year1():
TypeError: 'dict' object is not callable
第34行,在for key中,year1()中的值:
TypeError:“dict”对象不可调用
感谢您的任何见解 您是指第34行中的
year1.items()
对于键,值在year1.items()中:
下一行=1
单元格(列=1,行=下一行,值=键)
单元格(列=2,行=下一行,值=值)
下一行+=1
从上的python文档:
在字典中循环时,可以使用items()方法同时检索键和相应的值
骑士={'gallahad':'the pure','robin':'the brave'}
>>>对于骑士中的k,v。项()
... 印刷品(k,v)
...
纯洁的加拉赫
勇敢的罗宾
哇,太简单了,真不敢相信我错过了。年份1.items()工作正常。谢谢@willcrack
line 34, in <module> for key,values in year1():
TypeError: 'dict' object is not callable