我有下面这段代码,我在其中解析字典中的数据,并使用pyodbc库将数据生成一个表.
import pyodbc
data = {
"demographic": [
{
"id": 1,
"country": {
"code": "AU",
"name": "Australia"
},
"state": {
"name": "New South Wales"
},
"location": {
"time_zone": {
"name": "(UTC+10:00) Canberra, Melbourne, Sydney",
"standard_name": "AUS Eastern Standard Time",
"symbol": "AUS Eastern Standard Time"
}
},
"address_info": {
"address_1": "",
"address_2": "",
"city": "",
"zip_code": ""
}
},
{
"id": 2,
"country": {
"code": "AU",
"name": "Australia"
},
"state": {
"name": "New South Wales"
},
"location": {
"time_zone": {
"name": "(UTC+10:00) Canberra, Melbourne, Sydney",
"standard_name": "AUS Eastern Standard Time",
"symbol": "AUS Eastern Standard Time"
}
},
"address_info": {
"address_1": "",
"address_2": "",
"city": "",
"zip_code": ""
}
},
{
"id": 3,
"country": {
"code": "US",
"name": "United States"
},
"state": {
"name": "Illinois"
},
"location": {
"time_zone": {
"name": "(UTC-06:00) Central Time (US & Canada)",
"standard_name": "Central Standard Time",
"symbol": "Central Standard Time"
}
},
"address_info": {
"address_1": "",
"address_2": "",
"city": "",
"zip_code": "60611"
}
}
]
}
result = [(d["id"], d["country"]["name"], d["address_info"]["zip_code"]) for d in data["demographic"] if d["country"]["code"] == "US"]
现在我需要将这个结果写入一个表,该表的id、Country_Name、Zip
我正在try 下面的代码,但不确定如何循环遍历国家代码为US的所有记录,并将值映射到参数标记.我有游标设置,但不知道如何从Python词典中读取内容.
for r in result:
sql = """INSERT INTO tname (id, country_name, zip) VALUES (?, ?, ?)"""
cursor.execute(sql, params)
conn.commit()