정렬된 사전의 맨 앞에 요소를 삽입해야 하는 경우 '업데이트' 방법을 사용할 수 있습니다.
아래는 동일한 데모입니다 -
예시
from collections import OrderedDict
my_ordered_dict = OrderedDict([('Will', '1'), ('James', '2'), ('Rob', '4')])
print("The dictionary is :")
print(my_ordered_dict)
my_ordered_dict.update({'Mark':'7'})
my_ordered_dict.move_to_end('Mark', last = False)
print("The resultant dictionary is : ")
print(my_ordered_dict) 출력
The dictionary is :
OrderedDict([('Will', '1'), ('James', '2'), ('Rob', '4')])
The resultant dictionary is :
OrderedDict([('Mark', '7'), ('Will', '1'), ('James', '2'), ('Rob', '4')]) 설명
-
필요한 패키지를 가져옵니다.
-
OrderedDict'를 사용하여 정렬된 사전이 생성됩니다.
-
콘솔에 표시됩니다.
-
'update' 메소드는 키와 값을 지정하는 데 사용됩니다.
-
'move_to_end' 메소드는 키 값 쌍을 끝으로 이동하는 데 사용됩니다.
-
출력은 콘솔에 표시됩니다.