简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM