파이썬 딕셔너리
IT 위키
파이썬 딕셔너리(Dictionary)는 키(key)와 값(value)의 쌍으로 데이터를 저장하는 자료형으로, 연관 배열 또는 해시맵(HashMap)으로도 알려져 있다. 키를 통해 값을 빠르게 조회할 수 있으며, 중괄호({})를 사용하여 정의한다.
1 개요[편집 | 원본 편집]
딕셔너리는 변경 가능(mutable)하고 순서가 있는(파이썬 3.7 이상) 컬렉션 자료형이다. 각 키는 유일해야 하며, 값은 중복될 수 있다. 키는 문자열, 숫자, 튜플 등 해시 가능한(immutable) 자료형만 가능하다.
2 생성 방법[편집 | 원본 편집]
# 빈 딕셔너리
a = {}
# 초기값을 포함한 딕셔너리
person = {
"name": "Alice",
"age": 30,
"city": "Seoul"
}
3 주요 기능 및 메서드[편집 | 원본 편집]
3.1 항목 접근 및 수정[편집 | 원본 편집]
print(person["name"]) # Alice
person["age"] = 31 # 값 수정
person["job"] = "Engineer" # 새로운 키 추가
3.2 항목 삭제[편집 | 원본 편집]
del person["city"] # 특정 키 삭제
person.pop("age") # 키와 값 제거
person.clear() # 전체 삭제
3.3 반복문 사용[편집 | 원본 편집]
for key in person:
print(key, person[key])
for key, value in person.items():
print(key, value)
3.4 딕셔너리 관련 메서드[편집 | 원본 편집]
- dict.keys() — 키 목록 반환
- dict.values() — 값 목록 반환
- dict.items() — (키, 값) 쌍 반환
- dict.get(key, default) — 키가 없으면 기본값 반환
- dict.update(다른딕셔너리) — 병합
4 딕셔너리 컴프리헨션[편집 | 원본 편집]
조건이나 변환을 적용하여 딕셔너리를 생성할 수 있다.
squares = {x: x**2 for x in range(5)}
print(squares) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
5 중첩 딕셔너리[편집 | 원본 편집]
딕셔너리 내부에 또 다른 딕셔너리를 포함할 수 있다.
users = {
"alice": {"age": 30, "city": "Seoul"},
"bob": {"age": 25, "city": "Busan"}
}
print(users["alice"]["city"]) # Seoul
6 같이 보기[편집 | 원본 편집]
7 참고 문헌[편집 | 원본 편집]
- https://docs.python.org/3/library/stdtypes.html#dict
- Mark Lutz, Learning Python, O'Reilly Media