Python 按照 list 中的字典的某个 key 排序

需求:

有如下 list:

[{"a": "1.2", "img": "dd"}, {"a": "2.4", "img": "a"}, {"a": "5.3", "img": "c"}, {"a": "0.4", "img": "d"}]

现在要根据 list 中的 dict 的 key = a 的值来进行排序,

s=[
{"no":28,"score":90},
{"no":25,"score":90},
{"no":1,"score":100},
{"no":2,"score":20},

]
print "original s: ",s
# 单级排序,仅按照score排序
new_s = sorted(s,key = lambda e:e.__getitem__('score'))
print "new s: ", new_s
# 多级排序,先按照score,再按照no排序
new_s_2 = sorted(new_s,key = lambda e:(e.__getitem__('score'),e.__getitem__('no')))
print "new_s_2: ", new_s_2

字典排序

dict = {'a':21, 'b':5, 'c':3, 'd':54, 'e':74, 'f':0}
new_dict = sorted(dict.iteritems(), key=lambda d:d[1], reverse = True)
print new_dict

你可能感兴趣的:(Python 按照 list 中的字典的某个 key 排序)