使用itemgetter对dict列表进行排序

时间:2013-10-09 16:36:56

标签: python

这是我的字典:

a = [{"id":1,"data":{"age":16,"name":a}}, 
     {"id":3,"data":{"age":35,"name":b}}, 
     {"id":2,"data":{"age":9,"name":c}}]

我想按字段“年龄”对其进行排序。

使用lambda我使用:

sorted(a, key=lambda k: k['data']['age'])

如何使用itemgetter

执行此操作

2 个答案:

答案 0 :(得分:3)

你最好先在“a”,“b”和“c”中添加引号,否则你会在dict a和char“a”之间产生混淆

a = [{"id":1,"data":{"age":16,"name":"a"}}, 
     {"id":3,"data":{"age":35,"name":"b"}}, 
     {"id":2,"data":{"age":9,"name":"c"}}]

对于itemgetter

from operator import itemgetter

a = [{"id":1,"data":{"age":16,"name":"a"}}, 
     {"id":3,"data":{"age":35,"name":"b"}}, 
     {"id":2,"data":{"age":9,"name":"c"}}]

l=sorted(a, key = lambda k : itemgetter('age')(itemgetter('data')(k)) )

print (l)

答案 1 :(得分:0)

你可以这样使用它:

sorted(a, key = lambda k : itemgetter('age')(itemgetter('data')(k)) )

输出:

[{'data': {'age': 9, 'name': 'c'}, 'id': 2},
{'data': {'age': 16, 'name': 'a'}, 'id': 1},
{'data': {'age': 35, 'name': 'b'}, 'id': 3}]