简体   繁体   中英

Returning a sorted dictionary on flask

I've sorted my dictionary according to value and when I print it, it is sorted. However, when I return it on the flask module, it prints in alphabetical order. How do I make it return in sorted order by value?

Or may I ask, why is this the case?

response of the api request would look like something like this

{
  "bch_krw": {
    "timestamp": 1559285555322,
    "last": "513000",
    "open": "523900",
    "bid": "512100",
    "ask": "513350",
    "low": "476200",
    "high": "540900",
    "volume": "4477.20611753",
    "change": "-10900",
    "changePercent": "-2.08"
  },
  "fet_krw": {
    "timestamp": 1559285607258,
    ...
  },
  ...
}

PS if someone's wondering, something's off with the volume of the api which I have noticed them. Also, it's in KRW

@ app.route('/volume')
def print_volume():
    url = "https://api.korbit.co.kr/v1/ticker/detailed/all"

    resp = requests.get(url)

    obj = resp.json()
    # print(obj)

    total_vol = 0.0

    for i in obj:
        total_vol += float(obj[i]['volume'])

    #obj = sorted(obj.items(), key=lambda x: x[1]['volume'], reverse=True)

    print(obj)

    dict_vol = {}

    for i in obj:
        dict_vol[i[0]] = i[1]['volume']

    sorted_top_five = dict(
        sorted(dict_vol.items(), key=lambda item: item[1], reverse=True))

    print(sorted_top_five)


    return sorted_top_five

The reason behind getting your dictionary in alphabetical order is because of the serialization that happens behind the scenes from python dict type to JSON type, the default behavior is sorting the dict keys in alphabetical order.

so to serialize your dict as it is you are going to need json module. see below snippet

from flask import Flask
import requests
import json
app = Flask(__name__)

@app.route('/volume')
def print_volume():
    url = "https://api.korbit.co.kr/v1/ticker/detailed/all"

    resp = requests.get(url)
    
    obj = resp.json()

    total_vol = 0.0

    for i in obj:
        total_vol += float(obj[i]['volume'])

    dict_vol = {}

    for key in obj:
        dict_vol[key] = obj[key]['volume']

    sorted_top_five = dict(
        sorted(dict_vol.items(), key=lambda item: item[1], reverse=True))

    return json.dumps(sorted_top_five)

if __name__ == "__main__":
    app.run()

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