📌  相关文章
📜  Python|从给定字典中按排序顺序获取项目

📅  最后修改于: 2022-05-13 01:54:40.449000             🧑  作者: Mango

Python|从给定字典中按排序顺序获取项目

给定一个字典,任务是按排序顺序从字典中获取所有项目。让我们讨论一下我们可以完成这项任务的不同方法。

方法 #1:使用sorted()

# Python code to demonstrate
# to get sorted items from dictionary
  
# initialising _dictionary
ini_dict = {'a' : 'akshat', 'b' : 'bhuvan', 'c': 'chandan'}
  
# printing iniial_dictionary
print ("iniial_dictionary", str(ini_dict))
  
# getting items in sorted order
print ("\nItems in sorted order")
for key in sorted(ini_dict):
    print (ini_dict[key])
输出:
iniial_dictionary {'b': 'bhuvan', 'c': 'chandan', 'a': 'akshat'}

Items in sorted order
akshat
bhuvan
chandan


方法 #2:使用 d.items()

# Python code to demonstrate
# to get sorted items from dictionary
  
# initialising _dictionary
ini_dict = {'a' : 'akshat', 'b' : 'bhuvan', 'c': 'chandan'}
  
# printing iniial_dictionary
print ("iniial_dictionary", str(ini_dict))
  
# getting items in sorted order
print ("\nItems in sorted order")
for key, value in sorted(ini_dict.items()):
    print(value)
输出:
iniial_dictionary {'a': 'akshat', 'b': 'bhuvan', 'c': 'chandan'}

Items in sorted order
akshat
bhuvan
chandan

方法#3:使用运算符

# Python code to demonstrate
# to get sorted items from dictionary
  
import operator
  
# initialising _dictionary
ini_dict = {'a' : 'akshat', 'b' : 'bhuvan', 'c': 'chandan'}
  
# printing iniial_dictionary
print "iniial_dictionary", str(ini_dict)
  
# getting items in sorted order
print ("\nItems in sorted order")
for key, value in sorted(ini_dict.iteritems(),
                         key = operator.itemgetter(1), 
                         reverse = False):
    print key, " ", value
输出:
iniial_dictionary {'a': 'akshat', 'c': 'chandan', 'b': 'bhuvan'}

Items in sorted order
a   akshat
b   bhuvan
c   chandan