python - 将元组更改为字典,它如何正确设置键值?

标签 python sqlalchemy

我正在使用 SQLAlchemy 将数据插入 MySQL 数据库并进行查询。当我这样做时

result = db.engine.execute(query).fetchall() 它给了我看起来像这样的元组列表

结果 = [(1, 加拿大, 多伦多,...), (2, 加拿大, 温哥华,...),...] 我想了解当我将每个元组更改为字典时,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, 国家/地区: 加拿大, 城市: 多伦多,...}, {id:2, 国家/地区:加拿大, 城市: 温哥华,...},...]

当将元组转换为字典时,我们从未指定键名称,它是如何知道的?

最佳答案

它们不是普通的元组,而是RowProxy行为类似于元组和有序映射的实例。字符串键源自查询中的列名称。

关于python - 将元组更改为字典,它如何正确设置键值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57234885/

相关文章:

python - 每个工作日在两个日期之间出现的次数

python - 如何根据正则表达式从 pandas 数据集中选择行?

python - 在python中迭代mysql表

python - 如何复制 SQLAlchemy 查询对象?

python - 如何在 sqlalchemy 中将变量作为列名传递?

python - SQLAlchemy 中的过滤关系

Python Pandas 在中心指示器后去除字母 "|"

python - 我如何在 sqlalchemy 中表达这个查询?

python - SQLAlchemy 过滤时出错

python - Pocketsphinx + Gstreamer 竞赛条件? Pocketsphinx无法在Python脚本中同时收听音频+录音?