Python - 从给定的字典中按排序顺序获取项目
pythonserver side programmingprogramming更新于 2025/7/3 18:52:17
Python 字典具有键和值对。在某些情况下,我们需要根据键对字典的项目进行排序。在本文中,我们将看到从字典中的项目获取排序输出的不同方法。
使用 Operator 模块
Operator 模块具有 itemgetter 函数,该函数可以将 0 作为字典键的输入参数的索引。我们在 itemgetter 之上应用 sorted 函数并获取排序后的输出。
示例
dict = {12 : 'Mon', 21 : 'Tue', 17: 'Wed'}
import operator
print("\n给定字典", str(dict))
print ("按给定字典排序")
for k, n in sorted(dict.items(),key = operator.itemgetter(0),reverse = False):
print(k, " ", n)
输出
运行上述代码得到以下结果 −
给定字典 {12: 'Mon', 21: 'Tue', 17: 'Wed'}
按给定字典排序
12 Mon
17 Wed
21 Tue
使用 Sorted 方法
sorted 方法可直接应用于字典,对字典的键进行排序。
示例
dict = {12 : 'Mon', 21 : 'Tue', 17: 'Wed'}
#Using sorted()
print ("给定字典", str(dict))
print ("从给定字典排序")
for k in sorted(dict):
print (dict[k])
输出
运行上述代码得到以下结果 −
给定字典 {12: 'Mon', 21: 'Tue', 17: 'Wed'}
从给定字典排序
Mon
Wed
Tue
使用 dict.items()
我们还可以将 sorted 方法应用于 dict.items。在这种情况下,键和值都可以打印出来。
示例
dict = {12 : 'Mon', 21 : 'Tue', 17: 'Wed'}
#Using d.items()
print("\n给定字典", str(dict))
print ("按给定字典排序")
for k, i in sorted(dict.items()):
print(k,i)
输出
运行上述代码得到以下结果 −
给定字典 {12: 'Mon', 21: 'Tue', 17: 'Wed'}
按给定字典排序
12 Mon
17 Wed
21 Tue
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

