2. Dictionary
■ 개요
- 파이썬의 가장 강력한 데이터 컬렉션
- 파이썬에서 빠르게 데이터베이스 같은 연산을 가능하게 함
- 다른 언어에서는 다른 이름으로 불림
■ 특징
- {} 기호 혹은 dict()를 이용해 생성
- key : value의 쌍으로 이루어진다. 변환되는 값은 key로 사용 불가(예: list)
- key를 통해 value를 얻는다.
- {key1:value1, key2:value2, key3:value3 ...}
- 키 값이 반드시 문자열일 필요 없으며 변경 불가능한 데이터만 key가 될 수 있다.
- immutable 데이터인 문자열, 튜플, 숫자 값은 key가 될 수 있으나, 리스트는 key가 될 수 없다.
- 사전변수명[key](ex: dic['address']) 형식으로 찾을 경우 찾는 key가 없으면 예외를 발생한다.
- get 함수는 key가 없을 때 예외를 발생하는 대신 None을 리턴한다.
■ Dictionary 관련 함수
함수명 | 설명 |
min() | key값 중에서 최소값 (사전적 순서) |
max() | key값 중에서 최대값 (사전적 순서) |
get(key[,값]) | 특정 key를 통해 값을 얻음 해당 key가 없으면 default 값으로 대체 |
keys() | key값을 리스트로 얻어옴 |
values() | value값을 리스트로 얻어옴 |
items() | key와 value의 쌍을 튜플로 얻어옴 |
sorted(iterable, *, key=None, reverse=False) | 내장함수, 딕셔너리의 key값을 오름차순 정렬 |
score = {'홍길동':89, '임꺽정':88, '손오공':80, '전우치':67}
print('합계: ', sum(score.values()))
print('최고점: ', max(score.values()))
print(sorted(score, reverse=True)) # key값만 내림차순 정렬
합계: 324
최고점: 89
['홍길동', '전우치', '임꺽정', '손오공']
print(score.items())
for k,v in score.items():
print('이름:', k, '점수:', v)
dict_items([('홍길동', 89), ('임꺽정', 88), ('손오공', 80), ('전우치', 67)])
이름: 홍길동 점수: 89
이름: 임꺽정 점수: 88
이름: 손오공 점수: 80
이름: 전우치 점수: 67
score = {'홍길동':89, '임꺽정':88, '손오공':80, '전우치':67}
print(sorted(score.items(), reverse=True))
print(sorted(score.items(), reverse=False, key=lambda x:x[1])) # x에는 튜플 값이 들어감, 성적을 기준으로 정렬(value)
print(sorted(score.items(), reverse=False, key=lambda x:x[0])) # 이름을 기준으로 정렬(key)
['홍길동', '전우치', '임꺽정', '손오공']
[('홍길동', 89), ('전우치', 67), ('임꺽정', 88), ('손오공', 80)]
[('전우치', 67), ('손오공', 80), ('임꺽정', 88), ('홍길동', 89)]
[('손오공', 80), ('임꺽정', 88), ('전우치', 67), ('홍길동', 89)]
print(score['홍길동'])
# print(score['김철수']) # key error
print(score.get('김철수')) # None
print(score.get('김철수', 0)) # 김철수 값에 0을 넣어서 반환
89
None
0
x = dict() # 또는 x = {} # 딕셔너리 선언
x['name'] = '전우치'
x['phone'] = '010-1111-2222'
print(x) # 딕셔너리 안에 값을 넣어줌
{'name': '전우치', 'phone': '010-1111-2222'}
x = dict() # 또는 x = {} # 비어있는 딕셔너리 선언
x['name'] = '전우치'
x['phone'] = '010-1111-2222'
x['phone'] = '010-2222-3333' # 값을 변경
print(x)
{'name': '전우치', 'phone': '010-2222-3333'}
[문제] 단어 빈도수 구하기
- 문장 안에 포함된 각 단어의 빈도수를 구하여 딕셔너리로 결과를 출력하세요.
- 단어는 key가 되고 빈도수는 value가 된다.
# 비어있는 딕셔너리 선언
# 리스트에서 첫번째 단어를 가져옴, 첫 번째 단어가 딕셔너리 안에 포함되어 있는지 확인 (dic.get())
# 딕셔너리가 비어있으니 가져온 단어가 없음 -> 최초 등장한 단어 -> 횟수 1 (value)
word_list = song.replace('\n', ' ').lower().split()
mydic = {} # 결과를 저장할 변수
# 방법1
# for word in word_list:
# if mydic.get(word) == None: # if word not in mydic:
# mydic[word] =1
# else:
# mydic[word] += 1 # mydic[word] = mydic[word] + 1
# print(sorted(mydic.items(), key=lambda x:x[1], reverse=True)) # 빈도수를 기준으로 내림차순
# print('-'*30)
# 방법2
# for word in word_list:
# mydic[word] = mydic.get(word, 0) + 1 # 처음 나오는 값이면 None을 0으로 반환, 기존에 있는 값이면 +1
# print(sorted(mydic.items(), key=lambda x:x[1], reverse=True))
# print('-'*30)
# 방법3
for word in word_list:
mydic[word] = word_list.count(word)
print(sorted(mydic.items(), key=lambda x:x[1], reverse=True))
[('to', 14), ('you', 14), ('i', 12), ('that', 10), ("i'm", 8), ('it', 8), ('the', 8), ('but', 7), ("i've", 7), ('sorry', 7), ('anymore', 7), ('hello', 6), ('from', 6), ('tell', 6), ('for', 6), ('a', 5), ('everything', 4), ('say', 4), ('done', 4), ('can', 4), ('be', 4), ('when', 4), ('at', 4), ('of', 4), ('hello,', 3), ("it's", 3), ('other', 3), ('side', 3), ("must've", 3), ('called', 3), ('thousand', 3), ('times', 3), ('call,', 3), ('never', 3), ('seem', 3), ('home', 3), ('outside', 3), ('least', 3), ('tried', 3), ('breaking', 3), ('your', 3), ('heart', 3), ("don't", 3), ('matter,', 3), ('clearly', 3), ("doesn't", 3), ('tear', 3), ('apart', 3), ('me', 2), ('about', 2), ('we', 2), ('and', 2), ('how', 2), ('us', 2), ('are', 2), ('so', 2), ('ever', 2), ('out', 2), ('(other', 2), ('side)', 2), ('(thousand', 2), ('times)', 2), ('(outside)', 2), ("(i've", 2), ('tried)', 2), ('ooh-ooh,', 2), ('was', 1), ('wondering', 1), ('if', 1), ('after', 1), ('all', 1), ('these', 1), ('years', 1), ("you'd", 1), ('like', 1), ('meet', 1), ('go', 1), ('over', 1), ('they', 1), ("time's", 1), ('supposed', 1), ('heal', 1), ('ya', 1), ("ain't", 1), ('much', 1), ('healing', 1), ('hear', 1), ('me?', 1), ('in', 1), ('california', 1), ('dreaming', 1), ('who', 1), ('used', 1), ('were', 1), ('younger', 1), ('free', 1), ('forgotten', 1), ('felt', 1), ('before', 1), ('world', 1), ('fell', 1), ('our', 1), ('feet', 1), ("there's", 1), ('such', 1), ('difference', 1), ('between', 1), ('million', 1), ('miles', 1), ('you?', 1), ('typical', 1), ('talk', 1), ('myself,', 1), ('hope', 1), ("you're", 1), ('well', 1), ('did', 1), ('make', 1), ('town', 1), ('where', 1), ('nothing', 1), ('happened?', 1), ('no', 1), ('secret', 1), ('both', 1), ('running', 1), ('time', 1), ('ooh-ooh-ooh,', 1)]
'프로그래밍 언어 > Python' 카테고리의 다른 글
[Python] 문자열 다루기 (1) | 2023.10.29 |
---|---|
[Python] Collection - List (0) | 2023.10.29 |
[Python] Collection - Tuple (0) | 2023.10.27 |
[Python] Collection - Set (1) | 2023.10.27 |
[Python] Comprehension (List, Dictionary, Set) (0) | 2023.10.27 |