Python字典按键/值排序的几种方法
  TEZNKK3IfmPf 2023年11月14日 17 0

本文介绍对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}
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月14日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   2024年05月31日   34   0   0 python开发语言
  TEZNKK3IfmPf   2024年05月31日   27   0   0 python
  TEZNKK3IfmPf   2024年05月31日   28   0   0 python
TEZNKK3IfmPf