dict.update
기존 dict에 다른 dict 내용을 추가하거나, 수정하는 기능이다.
#추가
d
{'yellow': 3, 'blue': 4, 'red': 1}
add = dict({'orange':2, 'purple':0})
d.update(add)
#{'yellow': 3, 'blue': 4, 'red': 1, 'orange': 2, 'purple': 0}
#수정
d.update({'yellow': 9})
#{'yellow': 9, 'blue': 4, 'red': 1, 'orange': 2, 'purple': 0}
물론 추가와 수정 같이 진행할 수도 있다.
Collections.defaultdict
collections에서 deque와 Counter만 사용해오고 있었는데, defaultdict의 존재를 알게 되어서 정리를 해본다.
defaultdict는 알고 있는 dict의 subclass이다. dictionary + 추가적인 함수 포함된 버전이라고 생각하면 될 것같다. 출처에 표기된 python 문서에서는 아래의 경우에 defaultdict를 사용하면 편리하다고 한다.
List 형태의 value를 dict로 변환
from collections import defaultdict
s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)
dd = defaultdict(list) #type list로 지정 -> append 사용 가능
for k, v in s:
dd[k].append(v)
#defaultdict(<class 'list'>, {'yellow': [1, 3], 'blue': [2, 4], 'red': [1]})
#sorted 기능은 dict에도 있음
dd = sorted(dd.items())
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
https://docs.python.org/3/library/collections.html
collections — Container datatypes — Python 3.10.5 documentation
collections — Container datatypes Source code: Lib/collections/__init__.py This module implements specialized container datatypes providing alternatives to Python’s general purpose built-in containers, dict, list, set, and tuple. namedtuple() factory f
docs.python.org
'코딩놀이: python C C++' 카테고리의 다른 글
[프로그래머스 lv3] 표 편집, linked list (0) | 2022.09.24 |
---|---|
[프로그래머스 lv3] 양과 늑대, 백트래킹(Backtracking)과 DFS (0) | 2022.09.03 |
[python] 프로그래머스 lv3: 가장 먼 노드(그래프, bfs, bfs depth) (0) | 2022.07.23 |
[C] 백준 10817번 (0) | 2022.06.25 |
[C] 백준 공약수 (2436,) 등등 (0) | 2022.06.24 |