python字典排序的方法有哪些

31次阅读
没有评论

共计 879 个字符,预计需要花费 3 分钟才能阅读完成。

Python 字典排序的方法有以下几种:

  1. 使用 sorted() 函数:可以使用 sorted() 函数对字典的键或值进行排序。例如,使用 sorted() 函数对字典的键进行排序:
d = {'b': 2, 'a': 1, 'c': 3}
sorted_keys = sorted(d.keys())

输出结果为:[‘a’, ‘b’, ‘c’]
或者对字典的值进行排序:

d = {'b': 2, 'a': 1, 'c': 3}
sorted_values = sorted(d.values())

输出结果为:[1, 2, 3]

  1. 使用 itemgetter() 函数:可以使用 itemgetter() 函数对字典进行排序,可以根据字典的键或值进行排序。例如,根据字典的键进行排序:
from operator import itemgetter
d = {'b': 2, 'a': 1, 'c': 3}
sorted_items = sorted(d.items(), key=itemgetter(0))

输出结果为:[(‘a’, 1), (‘b’, 2), (‘c’, 3)]
根据字典的值进行排序:

from operator import itemgetter
d = {'b': 2, 'a': 1, 'c': 3}
sorted_items = sorted(d.items(), key=itemgetter(1))

输出结果为:[(‘a’, 1), (‘b’, 2), (‘c’, 3)]

  1. 使用 lambda 函数:可以使用 lambda 函数对字典进行排序,可以根据字典的键或值进行排序。例如,根据字典的键进行排序:
d = {'b': 2, 'a': 1, 'c': 3}
sorted_items = sorted(d.items(), key=lambda x: x[0])

输出结果为:[(‘a’, 1), (‘b’, 2), (‘c’, 3)]
根据字典的值进行排序:

d = {'b': 2, 'a': 1, 'c': 3}
sorted_items = sorted(d.items(), key=lambda x: x[1])

输出结果为:[(‘a’, 1), (‘b’, 2), (‘c’, 3)]
这些方法可以根据需要选择合适的方法对字典进行排序。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-21发表,共计879字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)