【问题标题】:Python Dict sort issuePython Dict 排序问题
【发布时间】: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


【解决方案1】:

items() 返回(key, value) 对。 t[1] 正在查看该对的第二部分,即值。做吧

expected_output=collections.OrderedDict(sorted(expected_output.items()))

这将给我们

OrderedDict([('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']), ('13', ['0.0']), ('14', ['8.0']), ('99', ['1.0'])])

如果你想像整数而不是字符串那样对键进行排序,你可以这样做

expected_output=collections.OrderedDict(sorted(expected_output.items(), 
                                               key=lambda pair: int(pair[0])))

得到

OrderedDict([('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'])])

【讨论】:

    猜你喜欢
    • 2015-08-07
    • 1970-01-01
    • 2012-10-15
    • 1970-01-01
    • 2019-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-17
    相关资源
    最近更新 更多