ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • collections 모듈 - defaultdict
    Engineering WIKI/Python 2022. 5. 12. 15:37
    # 예제(1) - dict vs defaultdict
    # 1-1. 기본 딕셔너리
    
    import collections
    ex1 = {'a':1, 'b':2}
    print(ex1)
    -------------------------
    print(ex1['c'])
    '''
    결과
    {'b': 2, 'a': 1}
    ---------------------------------
    # defaultdict의 초기값 생성
    KeyError: 'c'
    '''
    
    # 1-2. collections.defaultdict
    # defaultdict의 초기값 생성
    def default_factory():
    	return 'null'
    ex2 = collections.defaultdict(default_factory, a=1, b=2)
    print(ex2)
    print(ex2['c'])
    '''
    결과
    defaultdict(<function default_factory at 0x10ab50bf8>, {'b': 2, 'a': 1})
    null
    '''
    
    # 예제(2-1) - default_factory를 지정하지 않은 경우
    import collections
    ex2 = collections.defaultdict(a=1, b=2)
    print(ex2)
    print(ex2['c'])
    '''
    결과
    
    defaultdict(None, {'b': 2, 'a': 1})
    
    print(ex2['c'])
    KeyError: 'c'
    '''
    
    # 예제(2-1) - default_factory를 지정한 경우
    import collections
    def default_factory():
    	return 'null'
    
    ex2 = collections.defaultdict(default_factory, a=1, b=2)
    
    print(ex2)
    print(ex2['c'])
    '''
    결과
    
    defaultdict(<function default_factory at 0x10ab50c80>, {'b': 2, 'a': 1})
    
    null
    '''
    
    # 예제(3) - 다양한 default_factory
    import collections
    # 3-1. list
    ex_list = collections.defaultdict(list, a=[1,2], b=[3,4])
    print(ex_list)
    print(ex_list['c'])
    '''
    결과
    defaultdict(<class 'list'>, {'b': [3, 4], 'a': [1, 2]})
    []
    '''
    # 3-2. set
    ex_set = collections.defaultdict(set, a={1,2}, b={3,4})
    print(ex_set)
    print(ex_set['c'])
    '''
    결과
    defaultdict(<class 'set'>, {'b': {3, 4}, 'a': {1, 2}})
    set()
    '''
    # 3-3. int
    ex_int = collections.defaultdict(int, a=1, b=2)
    print(ex_int)
    print(ex_int['c'])
    '''
    결과
    defaultdict(<class 'int'>, {'b': 2, 'a': 1})
    0
    
    # 예제(4) - 리스트(s)의 원소 개수 구하기
    import collections
    # 4-1. 기본 딕셔녀리(dict)
    s = ['a', 'b', 'c', 'b', 'a', 'b', 'c']
    d = {}
    
    for k in s:
    	d.setdefault(k, 0) # 기본 딕셔너리(d)의 초기값 지정
    	d[k] += 1
    
    print(list(d.items()))
    '''
    결과
    [('b', 3), ('a', 2), ('c', 2)]
    '''
    # 4-2. defaultdict 이용
    dd = collections.defaultdict(int)
    
    for k in s:
    	dd[k] += 1
    print(list(dd.items()))
    '''
    결과
    [('b', 3), ('a', 2), ('c', 2)]
    '''
    # 4-3. 번외 - collections.Counter()이용
    c = collections.Counter(s)
    print(list(c.items()))
    '''
    결과
    [('b', 3), ('a', 2), ('c', 2)]
    '''
    

    'Engineering WIKI > Python' 카테고리의 다른 글

    operator의 itemgetter를 사용해서 리스트 정렬  (0) 2022.05.17
    collections 모듈 - OrderedDict  (0) 2022.05.12
    collections 모듈 - namedtuple  (0) 2022.05.12
    collections 모듈 - deque  (0) 2022.05.12
    collections 모듈 - Counter  (0) 2022.05.12
    vars() 내장함수  (0) 2022.05.10
    파이썬 리스트 컴프리헨션  (0) 2022.05.04
    Python 데코레이터  (0) 2022.05.02
Designed by Tistory.