Skip to main content
 首页 » 编程设计

python之如何在 Python 中对字典进行排序

2025年05月04日32飞鱼

我想生成一个报告,其中我的第一列将包含我的 SQL 查询的持续时间。这应该按持续时间从最高到最低的顺序排序。

代码:

import os 
 
directory = "./" 
results = {} 
 
def isfloat(value): 
  try: 
    float(value) 
    return True 
  except ValueError: 
    pass 
 
for root,dirs,files in os.walk(directory): 
    for file in files: 
       if file.endswith(".csv"): 
           input_file=open(file, 'r') 
           for line in input_file: 
                if line: 
                    try: 
                        duration=line.split(',')[13].split(' ')[1] 
                        if isfloat(duration): # check if string is a float 
                            results[duration]=line 
                    except: 
                        pass 
 
output_file = open('report.csv', 'w') 
for k,v in sorted(results.items()): 
    print k 
    output_file.write(k + ',' + v) 
output_file.close() 

输出:

1266.114 
1304.450 
1360.771 
1376.104 
1514.518 
500.105 
519.432 
522.594 
522.835 
528.622 
529.664 

我想知道为什么 sorted() 函数排序函数会弄乱我的结果?

请您参考如下方法:

您的 key 是字符串,而不是数字。它们按字典顺序排序。

如果要数字排序,先转换为数字:

for k,v in sorted(results.items(), key=lambda k_v: float(k_v[0])):