0

I have been trying for the past two days to sort this out and i can't figure it out.

I have a list of dictionaries that needs to be printed out as a table, the employees need to be ranked by the number of properties sold, highest to lowest.

import tabulate

data_list = [
         {
          'Name': 'John Employee',
          'Employee ID': 12345,
          'Properties Sold': 5,
          'Commission': 2500,
          'Bonus to Commission': 0,
          'Total Commission': 2500
         },
         {
          'Name': 'Allie Employee',
          'Employee ID': 54321,
          'Properties Sold': 3,
          'Commission': 1500,
          'Bonus to Commission': 0,
          'Total Commission': 1500
         },
         {
          'Name': 'James Employee',
          'Employee ID': 23154,
          'Properties Sold': 7,
          'Commission': 3500,
          'Bonus to Commission': 525,
          'Total Commission': 4025
          }
         ]

header = data_list[0].keys()

rows = [x.values() for x in data_list]

print(tabulate.tabulate(rows, header))

Output:

Name              Employee ID    Properties Sold    Commission    Bonus to Commission    Total Commission
--------------  -------------  -----------------  ------------  ---------------------  ------------------
John Employee           12345                  5          2500                      0                2500
Allie Employee          54321                  3          1500                      0                1500
James Employee          23154                  7          3500                    525                4025

Output needed:

Name              Employee ID    Properties Sold    Commission    Bonus to Commission    Total Commission
--------------  -------------  -----------------  ------------  ---------------------  ------------------
James Employee          23154                  7          3500                    525                4025
John Employee           12345                  5          2500                      0                2500
Allie Employee          54321                  3          1500                      0                1500
Zyan
  • 3
  • 1
  • 1
    Does this answer your question? [How do I sort a list of dictionaries by a value of the dictionary?](https://stackoverflow.com/questions/72899/how-do-i-sort-a-list-of-dictionaries-by-a-value-of-the-dictionary) – doctorlove Sep 29 '22 at 14:46

2 Answers2

1

You can sort the list of dictionaries by the properties sold:

sorted_data_list = sorted(data_list, key=lambda x: x["Properties Sold"], reverse=True)

header = sorted_data_list[0].keys()

rows = [x.values() for x in sorted_data_list]

print(tabulate.tabulate(rows, header))
Tom McLean
  • 5,583
  • 1
  • 11
  • 36
0

Never used tabulate, I can suggest a solution in pandas

df = pd.DataFrame.from_records(data_list).sort_values(by='Properties Sold', ascending=False)
imburningbabe
  • 742
  • 1
  • 2
  • 13