자료의 개수
- 리스트 자료형과 마찬가지로 딕셔너리 자료형의 원소의 개수도 len 명령으로 구할 수 있다.
- 중복된 키 허용 x
기본딕셔너리 문법
선언
x = {"a": 10, "b": 20}
갱신, 입력
x["a"] = 30
삭제
del x["b"]
x.pop('b',None) #value 반환 ,None 설정시 키가 없더라도 에러발생x
키 확인
x.keys()
키 반복문
for k in x:
print(k)
값 확인
x.values()
값 반복문
for v in x.values():
print(v)
쌍 반복문
for k, v in x.items():
print("key [%s] => value [%d]" % (k, v))
결합
dic1 = {1:10, 2:20}
dic2 = {1:100, 3:300}
dic1.update(dic2)
print(dic1)
결과
{1: 100, 2: 20, 3: 300}
더 유용한 딕셔너리 (defaultdict)
- 외부라이브러리이기에 import colletions 를 해야한다.
- defaultdict()는 딕셔너리를 만드는 dict클래스의 서브클래스이다.
- 작동하는 방식은 거의 동일한데, defaultdict()는 인자로 주어진 객체(default-factory)의 기본값을 딕셔너리값의 초깃값으로 지정할 수 있다.
- 숫자, 리스트, 셋등으로 초기화 할 수 있기때문에 여러 용도로 사용할 수 있다.
- type을 int로 설정시, 키가 생성이 되면 기본적으로 값이 0이다. +-연산을 바로할 수 있다
- list나 set으로 타입 설정시, append나 add를 통해 수정을 할 수 있다.
선언
counter = defaultdict(int) # 괄호안에는 타입을 작성한다.
타입이 리스트일 경우
from collections import defaultdict
def groupWords(words):
grouper = defaultdict(list)
for word in words:
length = len(word)
grouper[length].append(word)
return grouper
타입이 set일 경우
from collections import defaultdict
def groupWords(words):
grouper = defaultdict(set)
for word in words:
length = len(word)
grouper[length].add(word)
return grouper
예제문제
https://yunzae.tistory.com/152
카카오2020인턴-보석쇼핑
소요시간: 40분 나의 정답코드 import collections def solution(gems): gemNum=len(set(gems)) lt=0 rt=0 selected = collections.defaultdict(int) answer=[0,1e9] selected[gems[lt]]+=1 while True: if len(selected)
yunzae.tistory.com
'Problem Solving > 파이썬 문법,함수' 카테고리의 다른 글
메소드안에 전역번수 가져오기 (0) | 2023.10.16 |
---|---|
lower(), upper(), ' '.join(리스트) (0) | 2023.09.17 |
sum, min, max (1) | 2023.09.16 |
set (0) | 2023.04.13 |
sort(), sorted() (0) | 2023.01.04 |