在返回列表嵌套字典时候,往往需要对数据进行一定的处理:
按照字典中某一个key排序
In [87]: a = [{"name": "牛郎", "age": 23},{"name":"许仙", "age": 20},{"name":"董永", "age": 18}]
In [88]: a
Out[88]:
[{‘name‘: ‘牛郎‘, ‘age‘: 23},
{‘name‘: ‘许仙‘, ‘age‘: 20},
{‘name‘: ‘董永‘, ‘age‘: 18}]
In [89]: a.sort(key=lambda x:(x[‘name‘], x[‘age‘])) # 根据字典中name,age排序
In [90]: a
Out[90]:
[{‘name‘: ‘牛郎‘, ‘age‘: 23},
{‘name‘: ‘董永‘, ‘age‘: 18},
{‘name‘: ‘许仙‘, ‘age‘: 20}]
In [91]: a.sort(key=lambda x:(x[‘age‘], x[‘name‘]))
In [92]: a
Out[92]:
[{‘name‘: ‘董永‘, ‘age‘: 18},
{‘name‘: ‘许仙‘, ‘age‘: 20},
{‘name‘: ‘牛郎‘, ‘age‘: 23}]
如果排序字段是数字类型,如果我们需要对该字段进行逆序排,也可以这么写:
a.sort(key=lambd x :(x[‘name‘], -x[‘age‘]))
原文地址:http://blog.51cto.com/10412806/2174512
时间: 2024-10-31 13:12:47