3.Dictionary
- 값을 키(key)-값(value) 쌍으로 묶어서 저장하는 자료구조이다.
(리스트의 값들의 인덱스에 이름을 붙인 형태 - key) - key-value 쌍으로 묶은 데이터 한개를 item 또는 entry라고 한다.
Dictionary 생성
- 구문
- { 키 : 값, 키 : 값, 키 : 값 }
- dict(key=value, key=value) 함수 이용
- 키(key)는 불변(Immutable)의 값들만 사용 가능하다. (숫자, 문자열, 튜플) 일반적으로 문자열을 사용한다.
- dict() 함수를 사용할 경우 key는 변수로 정의한다
예)
customer_info = {"name" :"홍길동",
"age" : 20,
"nickname" : "박명수",
"email": "abc@abc.com",
"address" : "서울",
"hobby" :['게임', '스포츠']}
#KEY는 중복 허용 안함. VAlUE는 중복 허용함.
d = {"name":"홍길동","nickname": "홍길동"}
#같은 key가 들어가면 마지막에 추가된 것만 남는다.(변경)
d2 = {"name":"홍길동", "name" : "유재석", "name":"박명수"} ->{'name': '박명수'}
원소 조회 및 변경
- 조회: key값을 식별자로 지정 -> value 출력
- dictionary[ key ]
- 없는 키로 조회 시 KeyError 발생
- 변경
- dictionary[ key ] = 값
- 있는 key값에 값을 대입하면 변경이고 없는 key 일 경우는 새로운 item을 추가하는 것
#조회
customer_info["name"]
#추가/변경
cutomer_info["tall"] = 182.33 #추가 :없는 키 = 값
Dictionary 연산자
- in, not in 연산자
- 값 in dictionary
- dictionary의 Key로 값이 있으면 True, 없으면 False 반환
- 값 not in dictionary
- dictionary의 Key로 값이 없으면 True, 있으면 False 반환
- 값 in dictionary
- len(dictionary)
- dictionary의 Item의 개수 반환
"홍길동" in customer_info -> False #value가 있는 지 확인 불가
# in,not in은 key 가 있는지/없는지 여부
"name" in customer_info -> True
주요 메소드
item 반환 : get
삭제 : pop,clear, del
조회 : items, keys,values
customer_info = {'name': '홍길동',
'age': 20,
'nickname': '박명수',
'email': 'abc@abc.com',
'hobby': ['게임', '스포츠']}
customer_info.get("name")
customer_info.get("weight", -1) #-1 : default값(weight키가 없으면 반환할 값을 설정)
#반환하면서 제거
v = customer_info.pop("address") #address의 값을 반환하면서 제거
print(v)
customer_info
#제거
del customer_info['email'] #삭제만
customer_info
customer_info.keys() #key값들만 모아서 반환
customer_info.values() #value들만 모아서 반환
customer_info.items() #key, value를 튜플로 묶어서 반환
customer_info.clear()
'Tools > Python' 카테고리의 다른 글
[python] 04.제어문 컴프리헨션 | 제어문(조건문,반복문)과 간단한 제어문(컴프리헨션)을 배워보자 (1) | 2023.12.31 |
---|---|
[python] 03.자료구조 | Set (0) | 2023.10.24 |
[python] 03.자료구조 | Tuple (1) | 2023.10.24 |
[python] 03.자료구조 | List (1) | 2023.10.24 |
[python] 01. python 변수 - 02. 데이터 타입 정리 | 변수/데이터 타입/문자열/형변환 (0) | 2023.10.24 |