Python – 按元组键积对字典进行排序
给定带有元组键的字典,按键的元组积对字典项进行排序。
Input : test_dict = {(2, 3) : 3, (6, 3) : 9, (8, 4): 10, (10, 4): 12}
Output : {(2, 3) : 3, (6, 3) : 9, (8, 4): 10, (10, 4): 12}
Explanation : 6 < 18 < 32 < 40, key products hence retains order.
Input : test_dict = {(20, 3) : 3, (6, 3) : 9, (8, 4): 10, (10, 4): 12}
Output : {(6, 3) : 9, (8, 4): 10, (10, 4): 12, (20, 3) : 3, }
Explanation : 18 < 32 < 40 < 60, key products hence adjusts order.
方法 #1:使用字典理解 + lambda + sorted()
这是可以执行此任务的方式之一。在此,我们使用 sorted() 执行 sort(),并且 lambda函数用于计算可以执行排序的乘积。
Python3
# Python3 code to demonstrate working of
# Sort dictionary by Tuple Key Product
# Using dictionary comprehension + sorted() + lambda
# initializing dictionary
test_dict = {(5, 6) : 3, (2, 3) : 9, (8, 4): 10, (6, 4): 12}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# sorted() over lambda computed product
# dictionary comprehension reassigs dictionary by order
res = {key: test_dict[key] for key in sorted(test_dict.keys(), key = lambda ele: ele[1] * ele[0])}
# printing result
print("The sorted dictionary : " + str(res))
Python3
# Python3 code to demonstrate working of
# Sort dictionary by Tuple Key Product
# Using dict() + sorted() + lambda
# initializing dictionary
test_dict = {(5, 6) : 3, (2, 3) : 9, (8, 4): 10, (6, 4): 12}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# sorted() over lambda computed product
# dict() used instead of dictionary comprehension for rearrangement
res = dict(sorted(test_dict.items(), key = lambda ele: ele[0][1] * ele[0][0]))
# printing result
print("The sorted dictionary : " + str(res))
输出
The original dictionary is : {(5, 6): 3, (2, 3): 9, (8, 4): 10, (6, 4): 12}
The sorted dictionary : {(2, 3): 9, (6, 4): 12, (5, 6): 3, (8, 4): 10}
方法 #2:使用 dict() + sorted() + lambda
上述功能的组合可以用来解决这个问题。在此,使用与上述方法类似的方法。唯一的区别是在计算键排序后使用 dict() 而不是字典理解完成的项目排列。
Python3
# Python3 code to demonstrate working of
# Sort dictionary by Tuple Key Product
# Using dict() + sorted() + lambda
# initializing dictionary
test_dict = {(5, 6) : 3, (2, 3) : 9, (8, 4): 10, (6, 4): 12}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# sorted() over lambda computed product
# dict() used instead of dictionary comprehension for rearrangement
res = dict(sorted(test_dict.items(), key = lambda ele: ele[0][1] * ele[0][0]))
# printing result
print("The sorted dictionary : " + str(res))
输出
The original dictionary is : {(5, 6): 3, (2, 3): 9, (8, 4): 10, (6, 4): 12}
The sorted dictionary : {(2, 3): 9, (6, 4): 12, (5, 6): 3, (8, 4): 10}