相关疑难解决方法(0)

如何按字典值对字典列表进行排序?

我有一个字典列表,并希望每个项目按特定的属性值排序.

考虑下面的数组,

[{'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 sorting dictionary list data-structures

1722
推荐指数
19
解决办法
69万
查看次数

如何按可以包含重复值的列表对字典列表进行排序?

上下文:
在 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)

python sorting dictionary list

0
推荐指数
1
解决办法
98
查看次数

标签 统计

dictionary ×2

list ×2

python ×2

sorting ×2

data-structures ×1