如何在Python中对字典进行排序?
问题描述:
我想生成一个报告,其中第一列将包含我的SQL查询的持续时间。应该按照最长持续时间和最低持续时间排序。如何在Python中对字典进行排序?
代码:
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()
功能排序功能是搞乱我的结果?
答
您的钥匙是字符串,不是数字。它们按字典顺序排序。
转换为数字第一,如果你想数字排序:
for k,v in sorted(results.items(), key=lambda k_v: float(k_v[0])):
+0
非常感谢! –
答
您可以将字符串实际上转换为浮动:
if isfloat(duration): # check if string is a float
results[float(duration)] = line
或:
try:
results[float(duration)] = line
except ValueError:
pass
所以你不要这里不需要你的isfloat()
函数。
这应该给你正确的排序输出。
令人误解的问题标题,这与排序字典无关。 – deceze