API GET 요청에서 가져온 사전을 복사하여 openpyxl을 사용하여 엑셀하려고합니다. 그러나 코드는 " 'dict'object not callable"오류를 생성합니다. 내 코드는 다음과 같습니다.
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
이로 인해 각각 자체 변수에 할당 된 여러 라이브러리가 생성됩니다. 모두 <class 'dict'>입니다. 다음을 실행하여 테스트합니다.
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...
문제가 발생하는 곳입니다. openpyxl을 사용하여 이러한 새 사전 중 하나를 Excel에 작성하려고하면 오류가 발생합니다.
32. workbook = Workbook()
33. sheet = workbook.active
34. for key,values in year1():
35. next_row = 1
36. sheet.cell(column=1 , row=next_row, value=key)
37. sheet.cell(column=2 , row=next_row, value=values)
38. next_row += 1
39.
40. document_name = "yr1"
41. fullfilename = os.path.join(r'filelocation',document_name+'.xlsx')
42. workbook.save(fullfilename)
결과 오류는 다음과 같습니다.
line 34, in <module> for key,values in year1():
TypeError: 'dict' object is not callable
통찰력을 가져 주셔서 감사합니다!
year1.items()
34 행 을 의미 했습니까 ?
for key,values in year1.items():
next_row = 1
sheet.cell(column=1 , row=next_row, value=key)
sheet.cell(column=2 , row=next_row, value=values)
next_row += 1
루핑 기술 에 대한 파이썬 문서에서 :
사전을 반복 할 때 items () 메서드를 사용하여 키와 해당 값을 동시에 검색 할 수 있습니다.
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'} >>> for k, v in knights.items(): ... print(k, v) ... gallahad the pure robin the brave
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다