【发布时间】:2015-02-17 06:32:03
【问题描述】:
runnerList = [{1:{"name":"John","height":173,"age":16}},
{2:{"name":"Fred","height":185,"age":18}},
{3:{"name":"Luke","height":181,"age":17}}]
我一直在尝试根据跑步者的年龄按升序对这个字典列表进行排序,但没有成功:(我试过了:
import operator
runnerList.sort(key=lambda x: x['age'], reverse=True)
但似乎什么也没发生。我该怎么做?
【问题讨论】:
-
因为你在另一个字典里面有一个字典。
-
你应该得到一个
KeyError,很难相信什么都没发生。 -
您使用包含单元素升序整数键字典的字典是否有某些原因?这是一个相当奇特的数据结构。
-
除非你有一些你没有提到的外部约束,否则像
[{"name": "John", "height": 173, "age": 16}, {"name": "Fred", "height": 185, "age": 18}, {"name": "Luke", "height": 181, "age": 17}]这样的简单字典列表会更容易处理。 -
转换为@ZeroPiraeus
[next(iter(x.values())) for x in runnerList]提出的数据模型
标签: python list sorting python-3.x dictionary