Python Forum
How do you sort a table by one column?? (of floats) - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How do you sort a table by one column?? (of floats) (/thread-7450.html)



How do you sort a table by one column?? (of floats) - sortedfunctionfails - Jan-11-2018

Been struggling all day to figure this out, every guide online only shows how to use the sorted() function to change a table by a column alphabetically, there is no help anywhere if you are trying to sort by floats. Wall

#!/usr/bin/python

import sys
import urllib2
import json
import operator
from tabulate import tabulate

def sort_table(table, col):
	return sorted(table, key=operator.itemgetter(col))

total_num_coins = 500
num_displayed_coins = 50
url = "https://api.coinmarketcap.com/v1/ticker/?convert=AUD&limit=" + str(total_num_coins)

chartheaders = ["Position","Name","Market Cap","USD","Volume 24h","Change 24h", "Change 7d"]

data = urllib2.urlopen(url).read()
data = json.loads(data)

xcount = 0
table = []

percentage_winner_table = []
percentage_winner_table_length = 10

for d in data[0:num_displayed_coins]:
	if xcount < num_displayed_coins:
		table.append([d['rank'],d['name'],d['market_cap_usd'],d['price_usd'],d['24h_volume_usd'],d['percent_change_24h'],d['percent_change_7d']])
	xcount = xcount + 1

print '\n~=Todays Top ' + str(percentage_winner_table_length) + ' Winners!=~'
for row in sort_table(table, 5):
	percentage_winner_table.append(row)

print tabulate(percentage_winner_table,chartheaders,numalign="left",stralign="left",floatfmt=".2f")
This outputs:

~=Todays Top 10 Winners!=~
Position    Name              Market Cap       USD       Volume 24h      Change 24h    Change 7d
----------  ----------------  ---------------  --------  --------------  ------------  -----------
33          Ardor             1540577101.00    1.54      4107470.00      -0.06         -19.96
2           Ethereum          127911164630.00  1319.99   9519530000.00   -0.51         38.31
44          Veritaseum        959632708.00     471.18    841014.00       -0.59         25.41
12          NEO               7919470000.00    121.84    325600000.00    -0.97         21.75
6           NEM               13521689998.00   1.50      99261000.00     -1.04         -19.47
19          Ethereum Classic  3677233548.00    37.13     823540000.00    -1.11         10.40
14          Monero            6340876774.00    406.78    255541000.00    -1.20         -1.21
42          DigiByte          1058699135.00    0.11      76977900.00     -1.56         39.76
20          Lisk              3377092764.00    28.90     96994400.00     -1.82         36.17
38          Steem             1261803080.00    5.12      14579900.00     -10.90        -33.96
49          Hshare            828758533.00     19.51     194733000.00    -15.01        -20.89
35          Dogecoin          1443036775.00    0.01      88577800.00     -2.01         38.57
9           Stellar           10006314001.00   0.56      234255000.00    -2.32         -37.13
5           Cardano           19973411403.00   0.77      224343000.00    -2.38         -35.32
As you can see it's listing them by column 5 alphabetically instead of numerically. (grrrr!)

How can i get the sorted() function to sort this table numerically?

Something simple i tried that failed:

    return sorted(table, key=float(operator.itemgetter(col)))
TypeError: float() argument must be a string or a number



RE: How do you sort a table by one column?? (of floats) - Windspar - Jan-11-2018

return sorted(table, key=lambda k: float(k[col]))



RE: How do you sort a table by one column?? (of floats) - sortedfunctionfails - Jan-11-2018

Thanks for the awesome tip, this code works for listing the lowest value first.

How might i list the highest value first? I tried adding 'return=True' like so:

return sorted(table, key=lambda k: float(k[col]), reverse=True)
But it fails like so:

  File "coin-analysis.py", line 42, in <lambda>
    return sorted(table, key=lambda k: float(k[col]), reverse=True)
TypeError: float() argument must be a string or a number



RE: How do you sort a table by one column?? (of floats) - sortedfunctionfails - Jan-11-2018

for row in reversed(sort_table(table, 5)):
Adding the reversed() function like so gets the reverse sort i need. :)

Thanks everyone!