python - 将元组更改为字典,它如何正确设置键值?
问题描述
我正在使用 SQLAlchemy 将数据插入 MySQL 数据库并进行查询。当我做
result = db.engine.execute(query).fetchall()
它给了我看起来像的元组列表
result = [(1, canada, toronto,...), (2, canada, vancouver,....),....]
我想了解,当我将每个元组更改为字典时,python 如何正确分配适当的键。
这是我的python代码:
with open('static/db/final_cities_countries.json') as f:
data = json.load(f)
# if data exists grab data, if not query again and store into db, then grab data
query = db.select([Aqi]).where(Aqi.Country == country)
result = db.engine.execute(query).fetchall()
if len(result) < 1:
list_of_cities = data[country]
for city in list_of_cities:
# store into db if aqi_call is ONLY successful with status:ok
if get_aqi(city) != None:
aqi_response = get_aqi(city)
lat = aqi_response['data']['city']['geo'][0]
lng = aqi_response['data']['city']['geo'][1]
time = aqi_response['data']['time']['s']
# creating instance of Aqi class(row in MySQL table) and inserting into aqi table
aqi_data = Aqi(country, city, aqi_response['data']['aqi'], lat, lng, time)
db.session.add(aqi_data)
db.session.commit()
# this time it will have more
query = db.select([Aqi]).where(Aqi.Country == country)
# result = [(id, country, city,...), (id, country, city,...), ...etc.]
result = db.engine.execute(query).fetchall()
# sending back list of dictionaries. [{id:x, country:y, city:z,...}, {},{},...]
return jsonify([dict(row) for row in result])
当我更改每个元组时,它会正确返回
[{id:1, country: canada, city:toronto,...}, {id:2, country:canada, city: vancouver,...},...]
在将元组转换为字典时,我们从未指定键名,它是如何知道的?
解决方案
它们不是普通tuple
的 s,而是RowProxy
表现得既像元组又像有序映射的实例。字符串键是从查询中的列名派生的。
推荐阅读
- javascript - 是否可以像 python 一样使用 Rapydscript 进行 API 调用?
- php - 如果订单包含来自特定产品类别的商品,则为 WooCommerce 订单号添加前缀
- python - 使用pyautowin python包编辑powerbi 2020子窗口中的文本
- java - 如何从听众那里获取 Cookie?
- python - 如何将自己的函数导入 .ipynb 笔记本?
- amazon-web-services - 如何在没有预先设置存储库的情况下开始为已经运行的 ElasticSearch 集群拍摄快照?
- reactjs - react-hook-form:使用 onBlur 模式时验证不起作用
- php - AlpineJS 和 Livewire 中的 DateTimePicker 问题
- javascript - 如何检查所选月份是当前月份
- python - 以 bool 数据类型打开字典