정렬된 값으로 사전을 필터링해야 하는 경우 목록 이해와 함께 '정렬' 방식을 사용합니다.
예
아래는 동일한 데모입니다.
my_list = [{'python': 2, 'is': 8, 'fun': 10},
{'python': 1, 'for': 10, 'coding': 9},
{'cool': 3, 'python': 4}]
print("The list is :")
print(my_list)
my_result = [index for index in my_list if sorted(
list(index.values())) == list(index.values())]
print("The resultant dictionary is :")
print(my_result) 출력
The list is :
[{'python': 2, 'fun': 10, 'is': 8}, {'python': 1, 'coding': 9, 'for': 10}, {'python': 4, 'cool': 3}]
The resultant dictionary is :
[{'python': 1, 'coding': 9, 'for': 10}] 설명
-
사전 요소 목록이 정의되어 콘솔에 표시됩니다.
-
목록 내포는 목록의 요소를 반복하는 데 사용되며 '정렬' 방법은 사전 값에 액세스하여 연속된 요소의 값과 같은지 확인하여 목록을 정렬하는 데 사용됩니다.
-
이것은 변수에 할당됩니다.
-
이 변수는 콘솔에 출력으로 표시됩니다.