순서가 있는 딕셔너리(OrderedDict)의 맨 앞에 새로운 요소를 삽입해야 하는 경우, update 메서드와 move_to_end 메서드를 함께 활용하면 간단하게 처리할 수 있습니다.
아래 예제를 통해 구체적인 구현 방법을 살펴보겠습니다.
예제 코드
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')])코드 설명
먼저
collections모듈에서OrderedDict를 임포트합니다.OrderedDict를 사용하여 순서가 유지되는 딕셔너리를 생성합니다.생성된 딕셔너리를 콘솔에 출력하여 초기 상태를 확인합니다.
update메서드를 사용하여 새로운 키와 값을 딕셔너리에 추가합니다. 이때 요소는 기본적으로 맨 뒤에 추가됩니다.move_to_end메서드에last = False옵션을 지정하면, 해당 키-값 쌍을 딕셔너리의 맨 앞으로 이동시킬 수 있습니다. 반대로last = True(기본값)로 설정하면 맨 뒤로 이동합니다.최종 결과를 콘솔에 출력하여 새로운 요소가 맨 앞에 삽입된 것을 확인할 수 있습니다.
이처럼 update와 move_to_end 메서드를 조합하면 OrderedDict의 원하는 위치에 손쉽게 요소를 삽입할 수 있습니다.