기존 자료 구조인 dictionary와 list의 활용 방법을 몇 가지 예제를 통해 살펴보고자 한다.
get 메서드는 key에 해당하는 value를 가져올 때 사용한다. 만약 key가 존재하지 않는다면, 두 번째 인자로 전달된 기본값을 반환한다.
a = {'name': 'pey', 'phone': '0119993323', 'birth': '1118'}
print(a.get('name')) # 'pey'
print(a.get('phone', 0)) # '0119993323'
import pandas as pd
word_count = pd.DataFrame({'단어': ['hello', 'world'], '빈도': [1, 2]})
# 첫 번째 방법
count_dic = word_count.set_index('단어')['빈도'].to_dict()
# 두 번째 방법
count_dic_alt = dict(zip(word_count['단어'], word_count['빈도']))
# 다중 dictionary인 경우
if key in my_dict:
my_dict[key][date] = df
else:
my_dict[key] = {'date': df}
여러 dictionary에 동일한 key가 있을 때, 각 key에 대한 value를 합치는 방법
dict_list = [{'a': 1}, {'a': 2}, {'a': 3}, {'b': 1}]
result = {
key: sum(d.get(key, 0) for d in dict_list)
for key in set().union(*dict_list) # 모든 딕셔너리 키들을 합친 유니크한 집합
}
my_list = ['1', '2', '3']
my_list = list(map(int, my_list))
a_list = [1, 2, 3, 4]
b_list = [3, 4, 5, 6]
difference = list(set(a_list) - set(b_list))
from collections import Counter
elements_list = ['apple', 'banana', 'apple', 'orange', 'banana', 'banana']
C = Counter(elements_list)
most_common = C.most_common(1) # 가장 많이 나타난 원소 찾기
d_cols = [k for k,v in C.items() if v==12] # 특정 횟수에 대한 원소 찾기