📘딕셔너리란?
- 키(key)와 값(value)을 쌍으로 묶어 저장하는 자료형
- 리스트나 튜플처럼 순서가 아닌, 키로 값을 저장하고 꺼내는 방식
{} 중괄호로 묶어 저장
- 각 요소는
key: value 형태로 저장
- 키는 중복될 수 없고, 값은 중복 가능
- 키를 통해 빠르게 값을 조회할 수 있음
- 수정, 추가, 삭제가 모두 가능한 가변 자료형
- 키는 불변 자료형이어야 함 (문자열, 숫자, 튜플 등)
- 값은 어떤 자료형도 가능 (리스트, 딕셔너리 등)
person = {
'name': 'yoo',
'age': 28,
'city': 'Tokyo'
}
print(dict)
print(dict['name'])
🔎 딕셔너리 다루기
1. 딕셔너리 생성
1.1 {} 중괄호를 사용한 생성
student = {
'id': 'abc',
'name': 'hengu',
'age': 12
}
1.2 dict() 함수를 사용한 생성
car = dict(brand='BMW', model='m340i', year=2025)
print(car)
items = [('apple', 2), ('banana', 3)]
fruit_dict = dict(items)
print(fruit_dict)
2. 딕셔너리 요소 다루기
2-1 딕셔너리 요소 접근
person = {'name': 'Alice', 'age': 25, 'city': 'Tokyo'}
print(person['name'])
print(person['age'])
print(person.get('city'))
print(person.get('country'))
print(person.get('country', 'JAPAN'))
2-2. 딕셔너리 요소 변경
person = {'name': 'Alice', 'age': 25, 'city': 'Tokyo'}
person['age'] = 26
print(person)
2-3. 딕셔너리 요소 추가
person = {'name': 'Alice', 'age': 25, 'city': 'Tokyo'}
person['country'] = 'JAPAN'
print(person)
2-4. 딕셔너리 요소 삭제
person = {'name': 'Alice', 'age': 25, 'city': 'Tokyo'}
del person['city']
print(person)
age = person.pop('age')
print(age)
print(person)
person.clear()
print(person)
3. 딕셔너리 메서드
3-1. keys()
person = {'name': 'Alice', 'age': 25, 'city': 'Tokyo'}
dict_keys = person.keys()
print(dict_keys)
3-2. values()
person = {'name': 'Alice', 'age': 25, 'city': 'Tokyo'}
dict_values = person.values()
print(dict_values)
3-3. items()
person = {'name': 'Alice', 'age': 25, 'city': 'Tokyo'}
dict_items = person.items()
print(dict_items)
3-4. update()
- 기존 딕셔너리에 여러 개의 키-값을 한 번에 추가하거나 수정
- 이미 존재하는 키는 값이 변경되고, 존재하지 않는 키는 새로 추가됨
person = {'name': 'Alice', 'age': 25, 'city': 'Tokyo'}
person.update({'age': 30, 'city': 'Osaka'})
print(person)
4. 딕셔너리의 반복문 활용
- 딕셔너리의 각 요소에 접근하거나 처리하기 위해 반복문을 사용할 수 있음
4-1. 키를 통한 반복
for key in person:
print(key, person[key])
4-2. keys() 메서드를 통한 반복
for key in person.keys():
print(key)
4-3. values() 메서드를 통한 반복
for value in person.values():
print(value)
4-4. items() 메서드를 통한 반복
for key, value in person.items():
print(f'{key}: {value}')
4-5. keys(), values(), items() 추가
keys(), values(), items()는 view 객체를 반환
- 필요 시
list()로 변환해서 사용할 수 있음
for key in list(person.keys()):
print(key)
5. 딕셔너리 컴프리헨션
- 간결하고 효율적인 방법으로 새로운 딕셔너리를 생성하는 문법
new_dict = {key_expression: value_expression for item in iterable}
squares = {x: x**2 for x in range(1, 6)}
print(squares)
og = {'banana': 2, 'cherry': 3, 'mango': 5, 'grape': 4}
filtered = {k: v for k, v in og.items() if v % 2 == 0}
print(filtered)
6. 딕셔너리에서 자주 사용하는 기능들
6-1. len()
person = {'name': 'Alice', 'age': 25, 'city': 'Tokyo'}
print(len(person))
6-2. in 연산자
person = {'name': 'Alice', 'age': 25, 'city': 'Tokyo'}
print('name' in person)
print('email' in person)
6-3. del 키워드
person = {'name': 'Alice', 'age': 25, 'city': 'Tokyo'}
del person['city']
del person
7. 중첩 딕셔너리
- 딕셔너리는 다른 딕셔너리를 값으로 가질 수 있음
students = {
'student1': {'name': 'Alice', 'age': 25},
'student2': {'name': 'Bob', 'age': 22},
'student3': {'name': 'Charlie', 'age': 23}
}
print(students['student2']['name'])
for student_id, info in students.items():
print(f'ID: {student_id}')
for key, value in info.items():
print(f' {key}: {value}')
8. 딕셔너리의 응용
8-1. 키로 사용할 수 없는 자료형
- 리스트나 다른 딕셔너리 등 가변 자료형은 키로 사용할 수 없음
- 가변 자료형: list, set, dict
- 불변 자료형: int, float, bool, tuple, string
8-2. 딕셔너리 정렬
scores = {"Alice": 88, "Bob": 95, "Charlie": 70}
print(sorted(scores.items(), key=lambda kv: kv[1]))
print(sorted(scores.items(), key=lambda kv: kv[1], reverse=True))
scores = {"Alice": 95, "Bob": 95, "Charlie": 70, "Dave": 88}
sorted_items = sorted(
scores.items(),
key=lambda kv: (-kv[1], kv[0])
)
8-3. 딕셔너리와 JSON 데이터
- 딕셔너리는 JSON 데이터와 구조가 유사
- 웹 프로그래밍에서 데이터를 주고 받을 때 자주 사용
import json
person = {'name': 'Alice', 'age': 25, 'city': 'New York'}
json_str = json.dumps(person)
print(json_str)
data = json.loads(json_str)
print(data)
⚙️ 자주 쓰는 딕셔너리 메서드
| 메서드 | 설명 | 팁 |
|---|
.keys() | 모든 키를 반환 | 반복문과 자주 쓰임, view 객체 |
.values() | 모든 값을 반환 | 반복문과 자주 쓰임, view 객체 |
.items() | (키, 값) 쌍을 튜플로 반환 | 반복문과 자주 쓰임, view 객체 |
.get(key) | 키에 해당하는 값을 반환 | 키가 없을 때 오류대신 None을 반환 |
.pop(key) | 키-값 쌍을 삭제하고 값 반환 | |
.update() | 딕셔너리를 병합/수정 | 여러 항목을 한 번에 추가, 수정할 때 유용 |
.clear() | 모든 항목 삭제 | |