코딩놀이: python C C++

[python] dict.update, collections: defaultdict

jiheek 2022. 7. 30. 16:48

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