0

When requesting data from an API I get a list with dictionaries but when I request to sort it, it doesn't fully sort all numbers.

Code that I run:

def getVolume(e):
    return e["priceChangePercent"]

tickers.sort(reverse=True,key=getVolume)
for x in tickers:
    print(x["symbol"]+" "+x["priceChangePercent"])

Result that I get:

DLTBNB 9.729
RLCBNB 9.327
BRDBNB 9.087
EVXETH 8.699
||More numbers that are being sorted correctly||DASHBNB 3.123
ARDRETH 3.093
MATICBNB 23.832
MATICUSDT 20.087
XMRETH 2.946
||Random 23 showing up that does not belong there||
BCHSVUSDC 0
NXSBTC -9.700
GASBTC -9.585
SKYBTC -9.357

Example of dictionary when requesting the data of a dic in the tickers list:

{'symbol': 'ETHBTC', 'priceChange': '-0.00121400', 'priceChangePercent': '-4.363', 'weightedAvgPrice': '0.02695265', 'prevClosePrice': '0.02782400', 'lastPrice': '0.02661100', 'lastQty': '3.29400000', 'bidPrice': '0.02661100', 'bidQty': '6.70600000', 'askPrice': '0.02661900', 'askQty': '19.09500000', 'openPrice': '0.02782500', 'highPrice': '0.02841700', 'lowPrice': '0.02616300', 'volume': '320008.07300000', 'quoteVolume': '8625.06693308', 'openTime': 1557612831863, 'closeTime': 1557699231863, 'firstId': 121467734, 'lastId': 121655972, 'count': 188239}
khelwood
  • 55,782
  • 14
  • 81
  • 108
Python_Noob
  • 51
  • 1
  • 5

1 Answers1

2

You're sorting strings, not numbers, your getVolume needs to convert the values to float first:

def getVolume(e):
    return float(e["priceChangePercent"])

Or, you can do the conversion in the key function if you want a string to be returned by the getVolume:

tickers.sort(reverse = True, key = lambda x : float(getVolume(x)))
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55