상세 컨텐츠

본문 제목

파이썬 컬렉션 타입 - 딕셔너리

인공지능/파이썬

by Ryuzy 2023. 9. 3. 19:18

본문

728x90
반응형

1. 딕셔너리

파이썬의 딕셔너리는 - 쌍을 저장하는 순서 없는 변경 가능한(mutable) 컬렉션입니다. (파이썬 3.7 이전까지는 순서 없음 (3.7 이후는 입력 순서를 유지하지만 "논리적으로는" 순서 없음으로 간주)

 

1. 생성

딕셔너리는 중괄호 {} 사용하여 생성하고, - 쌍들은 쉼표 , 구분됩니다. - 쌍은 콜론 :으로 구분됩니다.

dic1 = {}
print(dic1)
print(type(dic1))

dic2 = {1:'김사과', 2:'반하나', 3:'오렌지', 4:'이메론'}
print(dic2)
print(type(dic2))

print(dic2[1])
print(dic2[3])

dic3 = {'no':1, 'userid':'apple', 'name':'김사과', 'hp':'010-1111-1111'}
print(dic3)
print(dic3['userid'])
print(dic3['hp'])

 

2. 변경 가능

딕셔너리는 변경 가능합니다. 따라서, 딕셔너리에 - 쌍을 추가하거나 제거하거나, 기존의 키의 값을 변경할 있습니다.

dic4 = {1:'apple'}
print(dic4)

dic4[100] = 'banana'
print(dic4)

dic4[100] = 'orange' # 변경
print(dic4)

dic4[50] = 'melon'
print(dic4)

del dic4[100] # 삭제
print(dic4)

 

3. 키, 값의 제약

딕셔너리의 키는 변경 불가능한(immutable) 타입이어야 합니다. 예를 들어, 문자열, 정수, 튜플은 딕셔너리의 키로 사용할 있지만, 리스트는 딕셔너리의 키로 사용할 없습니다. 하지만 딕셔너리의 값은 어떤 타입이든 상관없습니다.

dic3 = {'no':1, 'userid':'apple', 'name':'김사과', 'hp':'010-1111-1111'}
print(dic3)

# 요소 추가
dic3['gender'] = 'female'
print(dic3)

# 요소의 값 변경
dic3['no'] = 10
print(dic3)

dic3['score'] = [100, 90, 40]
print(dic3)

# dic3[[10, 20, 30]] = ['십', '이십', '삼십']
# print(dic3)

dic3[(10, 20, 30)] = ['십', '이십', '삼십']
print(dic3)

dic3['과일'] = {'사과':'🍎', '딸기':'🍓', '수박':'🍉'}
print(dic3)

 

4. 함수와 메서드

딕셔너리는 여러 함수와 메소드를 가지고 있습니다.

dic3 = {'no':1, 'userid':'apple', 'name':'김사과', 'hp':'010-1111-1111'}
print(dic3)

# keys(): 딕셔너리의 모든 키를 반환
print(dic3.keys())

 

dic3 = {'no':1, 'userid':'apple', 'name':'김사과', 'hp':'010-1111-1111'}
print(dic3)

# values(): 딕셔너리의 모든 값을 반환
print(dic3.values())

 

dic3 = {'no':1, 'userid':'apple', 'name':'김사과', 'hp':'010-1111-1111'}
print(dic3)

# items(): 딕셔너리의 모든 키-값을 튜플로 반환
print(dic3.items())

 

dic3 = {'no':1, 'userid':'apple', 'name':'김사과', 'hp':'010-1111-1111'}
print(dic3)

# get(): 특정 키에 대한 값을 반환. 만약 키가 딕셔너리에 없으면 None을 반환
# None을 치환할 수 있는 문자열을 설정할 수 있음
print(dic3['userid'])
# print(dic3['gender']) # KeyError: 'gender'
print(dic3.get('userid'))
print(dic3.get('gender')) # None
print(dic3.get('gender', '성별 알수없음'))
print(dic3.get('name', '이름 알수없음'))

 

dic3 = {'no':1, 'userid':'apple', 'name':'김사과', 'hp':'010-1111-1111'}
print(dic3)

# pop(): 특정 키에 대한 값을 제거하고 제거된 값을 반환. 키가 없다면 에러
temp = dic3.pop('hp')
print(dic3)
print(temp)

 

dic3 = {'no':1, 'userid':'apple', 'name':'김사과', 'hp':'010-1111-1111'}
print(dic3)

# in: 딕셔너리에 특정 키가 있는지 확인
print('hp' in dic3)
print('010-1111-1111' in dic3)

 

728x90
반응형

'인공지능 > 파이썬' 카테고리의 다른 글

파이썬 연산자  (0) 2023.09.05
파이썬 컬렉션 타입 - 세트  (0) 2023.09.04
파이썬 컬렉션 타입 - 튜플  (0) 2023.09.03
파이썬 컬렉션 타입 - 리스트  (0) 2023.09.01
문자열 다루기  (0) 2023.08.25

관련글 더보기