📜  Python - 排序顺序字典项目配对

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

Python - 排序顺序字典项目配对

有时,在使用Python字典时,我们可能会遇到需要对字典项进行重新排序、按排序顺序配对键和值、最小配对到最小值、最大值到最大值等等的问题。这种应用可以发生在竞争领域和日常编程中。让我们讨论可以执行此任务的某些方式。

方法#1:使用zip() + sort() + keys() + values()
上述功能的组合可以用来解决这个问题。在此,我们使用 zip() 执行配对任务,排序由 sort() 处理。

# Python3 code to demonstrate working of 
# Sorted order Dictionary items pairing
# Using zip() + sort() + keys() + values()
  
# initializing dictionary
test_dict = {45 : 3, 7 : 8, 98 : 4, 10 : 12, 65 : 90, 15 : 19}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# Sorted order Dictionary items pairing
# Using zip() + sort() + keys() + values()
vals = list(test_dict.values())
vals.sort()
keys = list(test_dict.keys())
keys.sort()
res = dict(zip(keys, vals))
  
# printing result 
print("The sorted order pairing : " + str(res)) 
输出 :
The original dictionary is : {65: 90, 98: 4, 7: 8, 10: 12, 45: 3, 15: 19}
The sorted order pairing : {65: 19, 98: 90, 7: 3, 10: 4, 45: 12, 15: 8}

方法 #2:使用map() + values() + zip() + sorted()
上述功能的组合可以用来解决这个问题。在此,我们使用 sorted() 执行排序任务。 zip() 和 map() 用于进一步配对。

# Python3 code to demonstrate working of 
# Sorted order Dictionary items pairing
# Using map() + values() + zip() + sorted()
  
# initializing dictionary
test_dict = {45 : 3, 7 : 8, 98 : 4, 10 : 12, 65 : 90, 15 : 19}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# Sorted order Dictionary items pairing
# Using map() + values() + zip() + sorted()
res = dict(zip(*map(sorted, (test_dict, test_dict.values()))))
  
# printing result 
print("The sorted order pairing : " + str(res)) 
输出 :
The original dictionary is : {65: 90, 98: 4, 7: 8, 10: 12, 45: 3, 15: 19}
The sorted order pairing : {65: 19, 98: 90, 7: 3, 10: 4, 45: 12, 15: 8}