首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将元组改为字典,如何正确设置键值?

将元组改为字典,如何正确设置键值?
EN

Stack Overflow用户
提问于 2019-07-28 02:15:36
回答 1查看 71关注 0票数 1

我使用SQLAlchemy在MySQL数据库中插入数据并对其进行查询。当我这样做的时候

result = db.engine.execute(query).fetchall()它给出了元组列表,如下所示

我想知道,当我将每个元组改为字典时,result = [(1, canada, toronto,...), (2, canada, vancouver,....),....]是如何正确地分配适当的键的。

这是我的python代码:

代码语言:javascript
复制
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,...},...]

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-07-28 02:32:24

它们不是普通的tuple,而是行为既像元组又像有序映射的RowProxy实例。字符串键派生自查询中的列名。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57234885

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档