Python字典按键/值排序的几种方法

本文介绍对Python字典的按键和按值排序的几种方式。

按键排序

# 对字典按键排序
def sort_by_key(d):
	'''
	d.items() 返回元素为 (key, value) 的可迭代类型(Iterable),
	key 函数的参数 k 便是元素 (key, value),所以 k[0] 取到字典的键。
	'''
    return sorted(d.items(), key=lambda k: k[0])


def main():
    dic = {'a': 2018, 'z': 2019, 'b': 2017}
    print(sorted(dic))  # ['a', 'b', 'z']
    print(sort_by_key(dic))  # [('a', 2018), ('b', 2017), ('z', 2019)]
    print(dict(sort_by_key(dic)))  # {'a': 2018, 'b': 2017, 'z': 2019}


if __name__ == '__main__':
    main()

如上所示:

  1. 如果直接调用sorted函数,只会对字典的键进行排序,返回键排序后的列表['a', 'b', 'z']
  2. 通过自己编写sort_by_key函数,首先通过sorted 函数返回列表,然后其中包含的元素为 tuple: ('a', 2018), ('b', 2017), ('z', 2019)
  3. 如果想得到按键排序后的字典,可以通过dict函数将包含元组的列表转换为所需要的字典{'a': 2018, 'b': 2017, 'z': 2019}

按值排序

同理,如果我们只需要对sort_by_value稍微修改一下,就可以得到按值排序的结果:

def sort_by_value(d):
    return sorted(d.items(), key=lambda k: k[1])  # k[1] 取到字典的值。

def main():
    dic = {'a': 2018, 'z': 2019, 'b': 2017}
    print(sort_by_value(dic))  # [('b', 2017), ('a', 2018), ('z', 2019)]

if __name__ == '__main__':
    main()

collections模块的OrderedDict

from collections import OrderedDict

sort_dict_by_key = OrderedDict(dic)  # 默认按键排序
print(sorted_dict_by_key)  # OrderedDict([('a', 2018), ('z', 2019), ('b', 2017)])

sort_dict_by_value = OrderedDict(sorted(dic.items(), key=lambda k: k[1]))
print(sort_dict_by_value)  # OrderedDict([('b', 2017), ('a', 2018), ('z', 2019)])

operator模块

from operator import itemgetter


dic = {'a': 2018, 'z': 2019, 'b': 2017}
print('Original dictionary : ', dic)
sorted_d = dict(sorted(dic.items(), key=itemgetter(0)))
print('Dictionary in ascending order by key : ', sorted_d)
sorted_d = dict(sorted(dic.items(), key=itemgetter(1)))
print('Dictionary in ascending order by value : ', sorted_d)

结果:

Original dictionary :  {'a': 2018, 'z': 2019, 'b': 2017}
Dictionary in ascending order by key :  {'a': 2018, 'b': 2017, 'z': 2019}
Dictionary in ascending order by value :  {'b': 2017, 'a': 2018, 'z': 2019}

How do I sort a dictionary by value?

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值