pythonpython-3.xflask

Retain order when returning dict in flask


I have following function in my flask application, which returns a dictionary to my page.

@app.route('/search', methods=['POST'])
def search():

    type = request.form['type']
    search = request.form[type]

    results_dict = results.change_filters(type, search)
    print(results_dict)

    return results_dict

When i print the dictionary, it is in the correct order, but when returning it to my page, it suddenly loses the order. My question is, how would you have the dictionary retain its order when returned? If not possible, what alternatives would you recommend?


Solution

  • Had the same problem, it's actually a very simple solution

    when configuring your flask app simply set this config value:

    app = Flask(__name__)
    app.config["JSON_SORT_KEYS"] = False
    

    This should retain the order your dictionary all the way to your page.

    Happy Coding