繁体   English   中英

如何根据字典中某个键的最高值对字典列表进行排序?

[英]How to rank a list of dictionaries by the highest value of a certain key within the dictionary?

过去两天我一直在尝试解决这个问题,但我无法弄清楚。

我有一个需要打印成表格的字典列表,员工需要按照出售的房产数量从高到低排序。

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 需要:

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

您可以按出售的房产对字典列表进行排序:

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

从未使用过tabulate ,我可以在pandas中提出解决方案

df = pd.DataFrame.from_records(data_list).sort_values(by='Properties Sold', ascending=False)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM