表示错误在第103行,即
for key, value in sorted(ProductReport.items(), key=lambda item: item[1]):
我正在写一个可以在命令行上运行的脚本,使用Python 3。
根据您的评论,我假设您正在尝试排序的字典是嵌套的。从您尝试使用key=lambda item: item[1]
来看,我认为您希望按'totalunits'
进行排序。在这种情况下,像这样的操作可以工作。
{1: {'grossrevenue': 3, 'totalunits': 2, 'discountcost': 100}, 2: {'grossrevenue': 3, 'totalunits': 777, 'discountcost': 100}}
>>> d = _
>>> def sort_by_key(tup):
... return d[1]['totalunits']
...
>>> sorted(d.items(), key=sort_by_key)
[(1, {'grossrevenue': 3, 'totalunits': 2, 'discountcost': 100}), (2, {'grossrevenue': 3, 'totalunits': 777, 'discountcost': 100})]
>>> sorted(d.items(), key=lambda tup: tup[1]['totalunits'])
[(1, {'grossrevenue': 3, 'totalunits': 2, 'discountcost': 100}), (2, {'grossrevenue': 3, 'totalunits': 777, 'discountcost': 100})]
>>> sorted(d.items(), key=lambda tup: tup[1]['totalunits'], reverse=True)
[(2, {'grossrevenue': 3, 'totalunits': 777, 'discountcost': 100}), (1, {'grossrevenue': 3, 'totalunits': 2, 'discountcost': 100})]
>>>
如果你的意图不同,请让我知道。这个类似的问题可能对你有帮助。