【发布时间】:2018-11-07 18:05:37
【问题描述】:
我正在使用 Python 根据键对 dict 项进行排序。但是输出没有给出正确的排序。任何人都可以帮忙吗?谢谢!这是我的代码:
expected_output= {'13':['0.0'], '14':['8.0'], '99':['1.0'], '100':['1.0'],
'101':['0.0'], '102':['1.0'], '103':['1.0'], '104':['0.0'], '105':['0.0'],
'106':['1.0'], '107':['1.0'], '108':['0.0'], '109':['0.0']}
expected_output=collections.OrderedDict(sorted(expected_output.items(), key=lambda t: t[1]))
print("Expected Output:")
print(expected_output)
输出是:
Expected Output:
OrderedDict([('108', ['0.0']), ('101', ['0.0']), ('13', ['0.0']), ('104',
['0.0']), ('105', ['0.0']), ('109', ['0.0']), ('107', ['1.0']), ('102',
['1.0']), ('106', ['1.0']), ('99', ['1.0']), ('103', ['1.0']), ('100',
['1.0']), ('14', ['8.0'])])
【问题讨论】:
-
t[1]是值,而不是键。 (此外,您到处都有字符串,并且这些字符串按 Unicode 字典顺序排序,而不是按数字排序。) -
您的预期输出与您的描述不符 (
sort according to the keys)。此外,您还没有指定是否要将键排序为字符串或整数。
标签: python-3.x sorting dictionary