The pattern of checking to see if a key is already in a dictionary and assuming a default value if the key is not there is so common that there is a method called get() that does this for us
if name in counts:
x = counts[name]
else:
x = 0
위의 식은 count라는 key를 모아놓은 리스트 안에 name이 있을 경우, x를 value값으로 출력하고, 없을 경우 0을 출력하는 코드이다. key가 이미 있는지 확인하는 이 패턴은 너무 많이 사용하기 때문에 get이라는 메서드로 더 간편하게 확인해볼 수 있다.
x = counts.get(name, 0)
#0은 default 값이다.
이를 응용해서, key값이 있으면 value를 +1 하고, key가 없으면 딕셔너리에 새로운 key를 만들고 value를 0이라 하는 코드를 작성해 보았을 때,
counts = dict()
names = ['csev', 'cwen', 'csev', 'zqian', 'cwen']
for name in names:
counts[name] = counts.get(name, 0) + 1
print(counts)
#{'csev' : 2, 'zqian' : 1, 'cwen' : 2} 출력
이렇게 주어진 리스트 안에 같은 이름이 몇개 있는지 빈도수를 확인하는 딕셔너리를 만들 수 있다.
'Python' 카테고리의 다른 글
[TIL] 220821 딕셔너리에서 value값으로 정렬하기, 리스트 컴프리헨션 활용 (0) | 2022.08.21 |
---|---|
[TIL] 220819 구글 코랩의 파일 깃헙에 연동하기, 데이터 연동하는 방법 (0) | 2022.08.19 |
[TIL] 220815 파이썬 리스트에 map 사용하기 (0) | 2022.08.15 |
[Mini Project] 파이썬 클래스 연습하기 | 클래스 기능을 활용한 학교 - 학급 - 학생관리 프로그램 (1st ~ 3rd try) (0) | 2022.08.15 |
[TIL] 220808 파이썬 문자열 내장 함수 find( ), index( ) (0) | 2022.08.08 |