사전에서 키와 값을 정렬해야 하는 경우 '정렬' 방식을 사용할 수 있습니다.
아래는 동일한 데모입니다 -
예시
my_dict = {'Hi': [1, 6, 3],
'there': [2, 9, 6],
'Mark': [16, 7]}
print("The dictionary is : ")
print(my_dict)
my_result = dict()
for key in sorted(my_dict):
my_result[key] = sorted(my_dict[key])
print("The sorted dictionary is : " )
print(my_result) 출력
The dictionary is :
{'Hi': [1, 6, 3], 'there': [2, 9, 6], 'Mark': [16, 7]}
The sorted dictionary is :
{'Hi': [1, 3, 6], 'Mark': [7, 16], 'there': [2, 6, 9]} 설명
-
사전이 정의되어 콘솔에 표시됩니다.
-
빈 사전이 정의되었습니다.
-
사전은 반복되고 그 전에 정렬됩니다.
-
키가 다시 정렬되어 빈 사전에 할당됩니다.
-
정렬된 사전이 콘솔에 표시됩니다.