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?

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章