0

This function currently returns data in below format.

@app.route("/brands")
def get_brands():
    cursor = mysql.connect().cursor()
    cursor.execute("SELECT brand_id, brand_name from table_brands")
    data = cursor.fetchall()
    if data is None:
     return "No data"
    else:
        return jsonify(data)

[       
    [
    25,
    "Yardley"
  ],
  [
    65,
    "Zandu"
  ]
]

I want data to be returns as-

[       
    {
        "id":25,
        "name": "Yardley"

    },
    {
        "id": 65,
        "name": "Zandu"
    }
]

What is most pythonic way to get that?

Sébastien
  • 11,860
  • 11
  • 58
  • 78
Devesh Agrawal
  • 8,982
  • 16
  • 82
  • 131
  • 'most pythonic' is straight in the 'primarily opinion based' category. You should look into https://stackoverflow.com/questions/3300464/how-can-i-get-dict-from-sqlite-query – pvg May 28 '17 at 07:16

1 Answers1

0

If by pythonic you mean, Is there a one-liner that will transform your list, then this might be what you are after

def dictify(a):
    return [dict(zip(("id","name"),vv)) for vv in a]

>>> a=[[25, 'Yardley'], [65, 'Zandu']]
>>> dictify (a)
[{'id': 25, 'name': 'Yardley'}, {'id': 65, 'name': 'Zandu'}]
BoarGules
  • 16,440
  • 2
  • 27
  • 44
  • Thanks for your response. But i think this is not what i am looking for. Please check my current output and desired output. – Devesh Agrawal May 28 '17 at 07:59