반응형
[OrderedDict]
이름 그대로 순서를 가진 딕셔너리 객체입니다. 기본적으로 파이썬의 딕셔너리는 순서를 보장하지 않습니다. 그러나 딕셔너리에서 순서를 고정하여 사용할 필요가 있는 경우, OrderedDict를 사용하면 됩니다. OrderedDict는 순서를 보장합니다.
from collections import OrderedDict
d = OrderedDict()
d['math'] = 100
d['english'] = 85
d['science'] = 70
for k, v in d.items():
print(k, v)
'''
>>> 'math' 100
>>> 'english' 85
>>> 'science' 70
'''
딕셔너리 객체를 생성한 다음, 이를 정렬하여 OrderedDict로 다시 입력할 수도 있습니다. 이때 정렬에는 sorted() 함수를 사용합니다.
def sort_by_key(t):
return t[0]
from collections import OrderedDict
d = dict()
d['x'] = 100
d['a'] = 200
d['z'] = 300
d['y'] = 400
for k, v in OrderedDict(sorted(d.items(), key = sort_by_key)).items():
print(k, v)
'''
>>> [('a', 200), ('x', 100), ('y', 400), ('z', 300)]
'''
- dictionary와 OrderedDict 객체 끼리의 비교
딕셔너리 객체의 경우, 두 개의 딕셔너리에 같은 값을 서로 다른 순서로 입력하더라도 == 비교를 하면 True를 반환합니다. 그러나 OrderedDict는 입력된 순서가 다르면 == 비교의 결과로 False를 반환합니다.
반응형
'Python' 카테고리의 다른 글
[Python] 자료구조 - collections 모듈 - Counter (0) | 2023.11.10 |
---|---|
[Python] 자료구조 - collections 모듈 - defaultdict (0) | 2023.11.10 |
[Python] 자료구조 - collections 모듈 - deque (0) | 2023.11.10 |
[Python] 자료 구조 - 문자열(string) (1) | 2023.10.31 |
[Python] 자료 구조 - 딕셔너리(dictionary) (0) | 2023.10.31 |