collections.OrderedDict

collections.OrderedDict

1. OrderedDict 란

명칭 그대로 삽입 순서가 보장되는 dictionary 형태의 컬렉션이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
from collections import OrderedDict


od = OrderedDict.fromkeys('abcde')
print(od)
>>> OrderedDict([('a', None), ('b', None), ('c', None), ('d', None), ('e', None)])

od.move_to_end('c')
print(od.keys())
>>> odict_keys(['a', 'b', 'd', 'e', 'c'])

od.move_to_end('c', last=False)
print(od.keys())
>>> odict_keys(['c', 'a', 'b', 'd', 'e'])

d = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2}

print(OrderedDict(sorted(d.items(), key=lambda t: t[0]))) # Key 를 이용한 정렬
>>> OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])

print(OrderedDict(sorted(d.items(), key=lambda t: t[1]))) # Value 를 이용한 정렬
>>> OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])

print(OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))) # Key 값의 길이를 이용한 정렬
>>> OrderedDict([('pear', 1), ('apple', 4), ('banana', 3), ('orange', 2)])

2. dict vs OrderedDict

파이썬 3.7 이전 환경에서 아래 소스를 실행할 경우, OrderedDict 는 삽입 순서가 보장되며, Dictionary의 경우는 순서가 Set 연산자와 마찬가지로 보장되지 않는 것을 확인할 수 있다.

(삽입순서에 대한 정보가 내부적으로 관리되다보니 OrderedDict 가 dictionary 에 비해 메모리를 두배이상 사용.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
from collections import OrderedDict


od = OrderedDict()
od['c'] = 1
od['b'] = 2
od['a'] = 3
print(od.items())
>>> [('c', 1), ('b', 2), ('a', 3)]

d = {}
d['c'] = 1
d['b'] = 2
d['a'] = 3
print(d.items())
>>> [('a', 3), ('c', 1), ('b', 2)]

※ Python 3.7 부터는 dictionary 의 경우에도 삽입 순서가 보장됨.
(참조 URL)

3. OrderedDict 활용

사용자가 n 번 만큼 값을 입력하고 출력된 결과가 다음과 같을 때,
삽입순서가 보장되지 않는 파이썬 환경에서 OrderedDict 를 활용해 작성해보자.

- Input
9
BANANA FRIES 12
POTATO CHIPS 30
APPLE JUICE 10
CANDY 5
APPLE JUICE 10
CANDY 5
CANDY 5
CANDY 5
POTATO CHIPS 30

- Output
BANANA FRIES 12
POTATO CHIPS 60
APPLE JUICE 20
CANDY 20
1
2
3
4
5
6
7
8
9
10
11
12
13
# Problem Result Code
n = int(input())

ordered_dictionary = OrderedDict()

for _ in range(n):
item_name, space, net_price = input().rpartition(' ')

# dict.get('key', default) → key 값이 없으면 default 반환
ordered_dictionary[item_name] = ordered_dictionary.get(item_name, 0) + int(net_price)

for item_name, net_price in ordered_dictionary.items():
print(item_name, net_price)

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×