jun
jun

Reputation: 143

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,
    ...
  },
  ...
}

P.S 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

Upvotes: 1

Views: 980

Answers (2)

Ibrahim
Ibrahim

Reputation: 6088

Just adjust settings at the beginning of your flask app:

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

Credit goes to @Saeed Ir

Upvotes: 2

Ahmed Hany
Ahmed Hany

Reputation: 1040

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

Upvotes: 2

Related Questions