파이썬에서 딕셔너리(dictionary)는 키-값 쌍을 저장하는 가변적인 데이터 구조입니다. 딕셔너리는 중괄호({})로 감싸고, 콜론(:)을 사용하여 키와 값을 구분합니다. 키는 변경 불가능한(immutable) 데이터 타입이어야 하며, 중복을 허용하지 않습니다. 값은 어떤 데이터 타입이든 상관없습니다.
1. 딕셔너리 생성
딕셔너리는 중괄호를 사용하여 생성할 수 있으며, 키-값 쌍을 포함합니다.
# 빈 딕셔너리 생성 empty_dict = {} # 키-값 쌍을 포함하는 딕셔너리 생성 person = {"name": "Alice", "age": 25, "city": "New York"} |
또한 dict() 함수를 사용하여 생성할 수도 있습니다.
person = dict(name="Alice", age=25, city="New York") |
2. 딕셔너리 요소 접근 및 변경
키를 사용하여 딕셔너리의 값을 접근하거나 변경할 수 있습니다.
person = {"name": "Alice", "age": 25, "city": "New York"} # 값 접근 print(person["name"]) # "Alice" print(person["age"]) # 25 # 값 변경 person["age"] = 26 print(person["age"]) # 26 # 새로운 키-값 쌍 추가 person["job"] = "Engineer" print(person) # {"name": "Alice", "age": 26, "city": "New York", "job": "Engineer"} |
3. 딕셔너리 메서드
딕셔너리는 다양한 내장 메서드를 제공합니다.
요소 제거
person = {"name": "Alice", "age": 25, "city": "New York"} # 특정 키-값 쌍 제거 age = person.pop("age") print(age) # 25 print(person) # {"name": "Alice", "city": "New York"} # 임의의 키-값 쌍 제거 item = person.popitem() print(item) # ("city", "New York") (순서는 임의적) print(person) # {"name": "Alice"} # 모든 요소 제거 person.clear() print(person) # {} |
키와 값 확인
person = {"name": "Alice", "age": 25, "city": "New York"} # 키 확인 print(person.keys()) # dict_keys(['name', 'age', 'city']) # 값 확인 print(person.values()) # dict_values(['Alice', 25, 'New York']) # 키-값 쌍 확인 print(person.items()) # dict_items([('name', 'Alice'), ('age', 25), ('city', 'New York')]) |
키 존재 여부 확인
person = {"name": "Alice", "age": 25, "city": "New York"} print("name" in person) # True print("job" in person) # False |
기본값 설정
get() 메서드는 키가 존재하지 않을 때 기본값을 반환합니다.
person = {"name": "Alice", "age": 25, "city": "New York"} print(person.get("name")) # "Alice" print(person.get("job", "Unknown")) # "Unknown" |
딕셔너리 병합
update() 메서드는 다른 딕셔너리의 키-값 쌍을 추가하거나 업데이트합니다.
person = {"name": "Alice", "age": 25} additional_info = {"city": "New York", "job": "Engineer"} person.update(additional_info) print(person) # {"name": "Alice", "age": 25, "city": "New York", "job": "Engineer"} |
4. 딕셔너리 순회
딕셔너리를 순회하여 키와 값을 가져올 수 있습니다.
person = {"name": "Alice", "age": 25, "city": "New York"} # 키 순회 for key in person: print(key, person[key]) # 키와 값 순회 for key, value in person.items(): print(key, value) |
5. 딕셔너리 컴프리헨션
딕셔너리 컴프리헨션을 사용하여 간결하게 딕셔너리를 생성할 수 있습니다.
squares = {x: x*x for x in range(6)} print(squares) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25} |
딕셔너리는 키-값 쌍을 효율적으로 관리할 수 있는 매우 유용한 데이터 구조입니다. 다양한 메서드와 기능을 통해 복잡한 데이터 구조를 쉽게 다룰 수 있습니다.
'파이썬 문법' 카테고리의 다른 글
파이썬에서 클래스 핵심 개념 (0) | 2024.08.12 |
---|---|
파이썬에서 형 변환(type casting 또는 type conversion) (0) | 2024.08.11 |
파이썬에서 문자열은 문자들의 시퀀스. (0) | 2024.08.03 |
파이썬(Python)에서 연산자. (0) | 2024.08.03 |
파이썬에서 변수와 데이터 타입. (0) | 2024.08.02 |