将数据插入SQLite但获得KeyError - Python

时间:2018-04-14 18:55:49

标签: python python-requests

尝试将数据插入数据库但我不断收到此错误:

Traceback (most recent call last):
  File "business.py", line 25, in <module>
    data = fetch_data(con)
  File "business.py", line 18, in fetch_data
   result.append((entry['address'], entry['postalcode'],
KeyError: 'address'

仍然是python和编码的新手。感谢你的帮助,伙计们!

到目前为止我所拥有的:

import requests
import sqlite3

URL = 'http://url/url/url/{}.json'
def fetch_data(con):
    cur = con.cursor()
    cur.execute("SELECT identifier FROM restaurant WHERE res_creditnote = 'No' LIMIT 6")
    result = []
    for row in cur:
        r = requests.get(URL.format(row[0]))
        entry = r.json()
        result.append((entry['address'], entry['postalcode'],
                       entry['postal'], entry['statenumber'], entry['state'],
                       entry['countrycode'], entry['country']))
    return result

con = sqlite3.connect("business.db")
data = fetch_data(con)
cur = con.cursor()
cur.executemany('INSERT INTO hotel (address, postalcode, '
                'postal, statenumber, state, '
                'countrycode, country) VALUES (?, ?, ?, ?, ?, ?, ?);', data)
con.commit()
con.close()

修改

我尝试像这样获取json数据:

"businessaddress":{"address":"Stockholm road 11","postalcode":"045432","postal":"Stockholm","statenumber":"45141","state":"Stockholm","countrycode":"SW","country":"Sweden"}

2 个答案:

答案 0 :(得分:1)

它与SQL无关,而是与您的字典entry无关。显然,您正在检索的JSON中没有地址密钥。您可以通过在此行entry = r.json()

之后打印然后输入词典来尝试调试

答案 1 :(得分:1)

您的数据显示在包含密钥&#34; businessaddress&#34;的字典中。它本身就是一个包含其他键的字典。因此,您需要通过entry = r.json()['businessaddress'] 等方式访问它,或者通过将内部字典分配给临时变量并使用它:

mystring = input("enter the string ")