小陆同学

python 中文名:蟒蛇,设计者:Guido van Rossum

导航

python--如何给dict字典类型排序

python中的字典底层是树实现的,本身没有像列表一样可以排序,但是会有应用场景需要将字典排序

1、一个字典按照值排序
example:
d = {'lilee':25, 'wangyan':21, 'liqun':32, 'age':19}

print(sorted(d.items(), key=lambda item:item[1]))

# response:
# [('age', 19), ('wangyan', 21), ('lilee', 25), ('liqun', 32)]

2、列表嵌套字典,列表里存在多个字典,需要按照某一个键值对排序

response = [
    {'pId': '/opt/data/', 'id': '/opt/data/1.txt', 'name': '1.txt'},
    {'pId': '/opt/data/2020-04', 'id': '/opt/data/2020-04/data-2020-04-01-1.log.gz', 'name': '2020-04/data-2020-04-01-1.log.gz'},
    {'pId': '/opt/data/2020-04', 'id': '/opt/data/2020-04/data-2020-04-02-1.log.gz', 'name': '2020-04/data-2020-04-02-1.log.gz'},
    {'pId': '/opt/data/2020-04', 'id': '/opt/data/2020-04/data-2020-04-04-1.log.gz', 'name': '2020-04/data-2020-04-04-1.log.gz'},
    {'pId': '/opt/data/2020-04', 'id': '/opt/data/2020-04/data-2020-04-03-1.log.gz', 'name': '2020-04/data-2020-04-03-1.log.gz'},
    {'name': '2020-04', 'pId': '/opt/data/2020-04', 'id': '/opt/data/2020-04'},
    {'pId': '/opt/data/', 'id': '/opt/data/data.log', 'name': 'data.log'},
]

response.sort(key=lambda x: x['id'])

print(response)

# [{'pId': '/opt/data/', 'id': '/opt/data/1.txt', 'name': '1.txt'}, {'name': '2020-04', 'pId': '/opt/data/2020-04', 'id': '/opt/data/2020-04'}, {'pId': '/opt/data/2020-04', 'id': '/opt/data/2020-04/data-2020-04-01-1.log.gz', 'name': '2020-04/data-2020-04-01-1.log.gz'}, {'pId': '/opt/data/2020-04', 'id': '/opt/data/2020-04/data-2020-04-02-1.log.gz', 'name': '2020-04/data-2020-04-02-1.log.gz'}, {'pId': '/opt/data/2020-04', 'id': '/opt/data/2020-04/data-2020-04-03-1.log.gz', 'name': '2020-04/data-2020-04-03-1.log.gz'}, {'pId': '/opt/data/2020-04', 'id': '/opt/data/2020-04/data-2020-04-04-1.log.gz', 'name': '2020-04/data-2020-04-04-1.log.gz'}, {'pId': '/opt/data/', 'id': '/opt/data/data.log', 'name': 'data.log'}]
当然这都是正序排列,reverse=True反转参数

 

posted on 2020-04-17 23:08  小陆同学  阅读(2520)  评论(0编辑  收藏  举报