chaikov
chaikov

Reputation: 505

changing tuple to dictionary, how does it set key values correctly?

I am using SQLAlchemy to insert data into MySQL database and query it. When I do

result = db.engine.execute(query).fetchall() it gives me list of tuples which looks like

result = [(1, canada, toronto,...), (2, canada, vancouver,....),....] I want to understand how, when I change each tuple to dictionary python correctly assigns appropriate key.

this is my python code:

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])

when I change each tuple it correctly returns

[{id:1, country: canada, city:toronto,...}, {id:2, country:canada, city: vancouver,...},...]

When transforming tuple to dictionary we never specified key names, how does it know?

Upvotes: 1

Views: 177

Answers (1)

Ilja Everil&#228;
Ilja Everil&#228;

Reputation: 53007

They're not plain tuples, but RowProxy instances that behave both like tuples and ordered maps. The string keys are derived from the column names in the query.

Upvotes: 1

Related Questions