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

时间:2022-07-28
本文章向大家介绍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?