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

현서·2025년 1월 1일

파이썬

목록 보기
8/27
post-thumbnail

1. 딕셔너리

키-값 쌍을 저장하는 변경 가능한(mutable) 컬렉션

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

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

print(dic2[2])
print(dic2[4])

dic3 = {'no':1, 'userid':'apple', 'name':'김사과', 'hp':'010-1111-1111'}
print(dic3)
print(dic3['userid'])
print(dic3['hp'])
{}
<class 'dict'>
{1: '김사과', 2: '반하나', 3: '오렌지', 4: '이메론'}
<class 'dict'>
반하나
이메론
{'no': 1, 'userid': 'apple', 'name': '김사과', 'hp': '010-1111-1111'}
apple
010-1111-1111
dic4 = {1:'apple'}
print(dic4)

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

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

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

del dic4[100]
print(dic4)
{1: 'apple'}
{1: 'apple', 100: 'banana'}
{1: 'apple', 100: 'banana', 50: 'orange'}
{1: 'apple', 100: 'melon', 50: 'orange'}
{1: 'apple', 50: 'orange'}
dic2 = {1:'김사과', 2:'반하나', 3:'오렌지', 2:'이메론'}
# 키가 중복되면 값을 재저장
print(dic2)

del dic2[1]
print(dic2)
print(type(dic2))
{1: '김사과', 2: '이메론', 3: '오렌지'}
{2: '이메론', 3: '오렌지'}
<class 'dict'>

2. 딕셔너리의 키, 값의 제약

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

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)
{'no': 1, 'userid': 'apple', 'name': '김사과', 'hp': '010-1111-1111'}
{'no': 1, 'userid': 'apple', 'name': '김사과', 'hp': '010-1111-1111', 'gender': 'female'}
{'no': 10, 'userid': 'apple', 'name': '김사과', 'hp': '010-1111-1111', 'gender': 'female'}
{'no': 10, 'userid': 'apple', 'name': '김사과', 'hp': '010-1111-1111', 'gender': 'female', 'score': [100, 90, 40]}
{'no': 10, 'userid': 'apple', 'name': '김사과', 'hp': '010-1111-1111', 'gender': 'female', 'score': [100, 90, 40], (10, 20, 30): ['십', '이십', '삼십']}
{'no': 10, 'userid': 'apple', 'name': '김사과', 'hp': '010-1111-1111', 'gender': 'female', 'score': [100, 90, 40], (10, 20, 30): ['십', '이십', '삼십'], '과일': {'사과': '🍎', '딸기': '🍓', '수박': '🍉'}}

3. 딕셔너리의 함수와 메서드

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

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

# keys(): 딕셔너리의 모든 키를 반환
print(dic3.keys())
{'no': 1, 'userid': 'apple', 'name': '김사과', 'hp': '010-1111-1111'}
dict_keys(['no', 'userid', 'name', 'hp'])
dic3 = {'no':1, 'userid':'apple', 'name':'김사과', 'hp':'010-1111-1111'}
print(dic3)

# values(): 딕셔너리의 모든 값을 반환
print(dic3.values())
{'no': 1, 'userid': 'apple', 'name': '김사과', 'hp': '010-1111-1111'}
dict_values([1, 'apple', '김사과', '010-1111-1111'])
dic3 = {'no':1, 'userid':'apple', 'name':'김사과', 'hp':'010-1111-1111'}
print(dic3)

# items(): 딕셔너리의 모든 키-값을 튜플로 반환
print(dic3.items())
{'no': 1, 'userid': 'apple', 'name': '김사과', 'hp': '010-1111-1111'}
dict_items([('no', 1), ('userid', 'apple'), ('name', '김사과'), ('hp', '010-1111-1111')])
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', '이름 알수없음'))
{'no': 1, 'userid': 'apple', 'name': '김사과', 'hp': '010-1111-1111'}
apple
apple
None
성별 알수없음
김사과

★ get() : 특정 키에 대한 값을 반환. 키가 딕셔너리에 없으면 none 반환.

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

# pop(): 특정 키에 대한 값을 제거하고 제거된 값을 반환. 키가 없다면 에러
temp = dic3.pop('hp')
print(dic3)
print(temp)
{'no': 1, 'userid': 'apple', 'name': '김사과', 'hp': '010-1111-1111'}
{'no': 1, 'userid': 'apple', 'name': '김사과'}
010-1111-1111
dic3 = {'no':1, 'userid':'apple', 'name':'김사과', 'hp':'010-1111-1111'}
print(dic3)

# in: 딕셔너리에 특정 키가 있는지 확인
print('hp' in dic3)
print('010-1111-1111' in dic3)
{'no': 1, 'userid': 'apple', 'name': '김사과', 'hp': '010-1111-1111'}
True
False

→ in: 딕셔너리에 특정 '키'가 있는지 확인하므로, '값'을 넣는 경우 False 출력한다.


✔ 다시 정리해보기!

  • ✨ 딕셔너리는 키-값 쌍을 저장하는 변경 가능한 컬렉션이다.
  • 딕셔너리는 중괄호 {}를 사용하여 생성한다.
  • ✨ 딕셔너리의 키는 변경 불가능한 타입이어야 한다. (ex : 리스트는 딕셔너리의 키로 사용 X)

함수와 메서드

  • keys() : 딕셔너리의 모든 키 반환
  • values() : 딕셔너리의 모든 값을 반환
  • ✨ items() : 딕셔너리의 모든 키-값을 튜플로 반환
  • ✨ get() : 특정 키에 대한 값을 반환. 만약 키가 딕셔너리에 없으면 None을 반환. None을 치환할 수 있는 문자열을 설정할 수 있다.
  • pop() : 특정 키에 대한 값을 제거하고 제거된 값을 반환. 키가 없으면 에러
  • in() : 딕셔너리에 특정 키가 있는지 확인.
profile
The light shines in the darkness.

0개의 댓글