我正在使用Python根据键对字典项进行排序。但是输出没有给出适当的排序。有人可以帮忙吗?谢谢!这是我的代码:
{
label: 'Edit',
submenu: [
{
label: 'Compose',
accelerator: 'CmdOrCtrl+N',
click(menuItem, forcedWindow, options) {
if (forcedWindow) {
forcedWindow.webContents.sendInputEvent({type: 'keyUp', keyCode: 'c'});
}
}
}
]
}
输出为:
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)
答案 0 :(得分: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'])])