defaultdict2 setdefault() - dictionary의 키 존재 상관없이 setdefault() dict타입의 키 존재 여부를 모른 채 접근할 수 있다 A.setdefault(key, default) collections.defaultdict을 활용할 수 도 있다, 초기화시 default값을 넣어준다 A = defaultdict(list) @print_method def usual_dict(dict_data): """ dict[key]. """ newdata = {} for k, v in dict_data: if k in newdata: newdata[k].append(v) else: newdata[k] = [v] return newdata @print_method def setdefault_dict(dict_data): """ setdefault() method. """ n.. 2020. 9. 17. Array(list)의 원소 개수 카운팅 collections 의 defaultdict로 배열의 엘러먼트 카운트를 하나의 함수도 대신하기 collections.Counter를 사용하면된다 from collections import defaultdict s = ['a', 'b', 'c', 'b', 'a', 'b', 'c'] dd = defaultdict(int) for k in s: dd[k]+=1 print(dd) defaultdict(, {'a': 2, 'b': 3, 'c': 2}) >>> from collections import Counter >>> d = Counter(s) >>> print(d) Counter({'b': 3, 'a': 2, 'c': 2}) 2020. 6. 27. 이전 1 다음