-
python_딕셔너리coding 101 2022. 4. 13. 09:38
딕셔너리 = 여러 요소들을 갖는 컬렉션(집합)
중괄호 {} 이용, 항목은 키(key)와 값(value)로 구성되어있고 키와 값의 구분은 콜론(:)을 사용한다
딕셔너리 = {키1:값1, 키2:값2, ...}
딕셔너리의 각 요소는 추가/삭제/변경이 가능하다
그러나 값는 변경가능하고 키는 변경 불가능
항목의 순서 x = 인덱스 x
baseball = {'red':4, 'blue':3, 'green':5} baseball {'red':4, 'blue':3, 'green':5} #key와 value 추출 baseball.keys() dict_keys(['red', 'blue', 'green']) baseball.values() dict_values([4, 3, 5]) baseball.items() dict_items([('red', 4), ('blue', 3), ('green', 5)]) #키의 값 중에서 하나 추출 baseball["red"] 4 baseball.get("red") 4 #추가 x = {"a":10, "b":20, "c":30} x["d"] = 40 print(x) {"a":10, "b":20, "c":30, "d":40} #변경 x = {"a":10, "b":20, "c":30} x["b"] = 50 print(x) {"a":10, "b":50, "c":30} #삭제 x = {"a":10, "b":20, "c":30} del(x["c"]) print(x) {"a":10, "b":20} x = {"a":10, "b":20, "c":30} x.pop("c") #키의 값 리턴하고 삭제 30 x {"a":10, "b":20} x = {"a":10, "b":20, "c":30} x.popitem() #임의의 데이터 리턴 삭제 ("c",30) #항목이 있는지 검사 scores = {'korean':80, 'math':90, 'english':89} 'math' in scores True
#딕셔너리 키 정렬 y={'a':10,'d':50,'c':30} sorted(y) ['a', 'c', 'd'] #딕셔너리 값 정렬 sorted(y.values()) [10,30,50]
728x90반응형'coding 101' 카테고리의 다른 글
python_선택문 (0) 2022.04.27 python_set (0) 2022.04.13 python_튜플 (0) 2022.04.13 python_인덱싱 및 슬라이싱 (0) 2022.04.06 python_자료구조 리스트 (0) 2022.04.06