我有一个字典列表,并希望每个项目按特定的属性值排序.
考虑下面的数组,
[{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]
Run Code Online (Sandbox Code Playgroud)
排序时name,应该成为
[{'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}]
Run Code Online (Sandbox Code Playgroud) 上下文:
在 Python 3.9 中,即使存在重复项,按第二个列表对大多数对象的列表进行排序也很容易:
>>> sorted(zip([5, 5, 3, 2, 1], ['z', 'y', 'x', 'w', 'x']))
[(1, 'x'), (2, 'w'), (3, 'x'), (5, 'y'), (5, 'z')]
Run Code Online (Sandbox Code Playgroud)
如果要排序的列表包含字典,则排序通常会顺利进行:
>>> sorted(zip([3, 2, 1], [{'z':1}, {'y':2}, {'x':3}]))
[(1, {'x': 3}), (2, {'y': 2}), (3, {'z': 1})]
Run Code Online (Sandbox Code Playgroud)
问题:
但是,当要排序的列表包含重复项时,会出现以下错误:
>>>sorted(zip([5, 5, 3, 2, 1], [{'z':1}, {'y':2}, {'x':3}, {'w': 4}, {'u': 5}]))
*** TypeError: '<' not supported between instances of 'dict' and 'dict'
Run Code Online (Sandbox Code Playgroud)
这个问题对我来说非常疯狂:要排序的列表的值如何影响要排序的列表?
替代解决方案:
一种不太优雅的解决方案是按索引从列表中获取字典对象:
>>> sort_list = [5, 5, 3, 2, 1]
>>> …Run Code Online (Sandbox Code Playgroud)