租用问题

质量为本、客户为根、勇于拼搏、务实创新

< 返回租用问题列表

python字典排序的有什么方法,python字典 排序

发布时间:2023-10-11 23:34:02

python字典排序的有甚么方法

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)]
这些方法可以根据需要选择适合的方法对字典进行排序。