python列表嵌套字典,根据键的值排序

列表[{‘name’:‘wang’,‘age’:30},{‘name’:‘zhang’,‘age’:20},{‘name’:‘li’,‘age’:25}],以’age’排序,结果:[{‘name’: ‘zhang’, ‘age’: 20}, {‘name’: ‘li’, ‘age’: 25}, {‘name’: ‘wang’, ‘age’: 30}]

方法一:

import operator
lt = [{'name':'wang','age':30},{'name':'zhang','age':20},{'name':'li','age':25}]
sorted_lt = sorted(lt,key=operator.itemgetter('age'))
print(sorted_lt)

方法二:

lt = [{'name':'wang','age':30},{'name':'zhang','age':20},{'name':'li','age':25}]
#sorted_lt  = sorted(lt,key=lambda x:x['age'],reverse=False)
# print(sorted_lt )

你可能感兴趣的:(python基础,面试篇)