Python - 排序字典键和值列表
有时,在使用Python字典时,我们可能会遇到需要对其进行排序的问题,即 wrt 键,但也可能有一个变体,我们也需要对其值列表执行排序。让我们讨论一下可以执行此任务的特定方式。
Input : test_dict = {‘c’: [3], ‘b’: [12, 10], ‘a’: [19, 4]}
Output : {‘a’: [4, 19], ‘b’: [10, 12], ‘c’: [3]}
Input : test_dict = {‘c’: [10, 34, 3]}
Output : {‘c’: [3, 10, 34]}
方法 #1:使用sorted()
+ 循环
上述功能的组合可以用来解决这个问题。在此,我们首先对键的所有值进行排序,然后以粗略的方式执行键排序。
# Python3 code to demonstrate working of
# Sort Dictionary key and values List
# Using loop + dictionary comprehension
# initializing dictionary
test_dict = {'gfg': [7, 6, 3],
'is': [2, 10, 3],
'best': [19, 4]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Sort Dictionary key and values List
# Using loop + dictionary comprehension
res = dict()
for key in sorted(test_dict):
res[key] = sorted(test_dict[key])
# printing result
print("The sorted dictionary : " + str(res))
The original dictionary is : {‘gfg’: [7, 6, 3], ‘is’: [2, 10, 3], ‘best’: [19, 4]}
The sorted dictionary : {‘best’: [4, 19], ‘gfg’: [3, 6, 7], ‘is’: [2, 3, 10]}
方法 #2:使用字典理解 + sorted()
上述功能的组合可以用来解决这个问题。在此,我们在字典理解结构中执行双重排序任务。
# Python3 code to demonstrate working of
# Sort Dictionary key and values List
# Using dictionary comprehension + sorted()
# initializing dictionary
test_dict = {'gfg': [7, 6, 3],
'is': [2, 10, 3],
'best': [19, 4]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Sort Dictionary key and values List
# Using dictionary comprehension + sorted()
res = {key : sorted(test_dict[key]) for key in sorted(test_dict)}
# printing result
print("The sorted dictionary : " + str(res))
The original dictionary is : {‘gfg’: [7, 6, 3], ‘is’: [2, 10, 3], ‘best’: [19, 4]}
The sorted dictionary : {‘best’: [4, 19], ‘gfg’: [3, 6, 7], ‘is’: [2, 3, 10]}