💻 프로그래밍/Python

[파이썬] 딕셔너리(dictionary)

gameuiux 2024. 5. 27. 22:53
728x90
반응형

딕셔너리(dictionary)

파이썬 딕셔너리(dictionary)는 키(key)와 값(value) 쌍으로 이루어진 자료 구조

 

딕셔너리는 키를 통해 값을 빠르게 조회할 수 있으며,

키는 고유해야 하고 변경할 수 없는 자료형이어야 한다.

 

값은 어떤 자료형도 될 수 있다.

 

 

 

딕셔너리 생성 및 기본 사용법

딕셔너리 생성
1. 빈 딕셔너리 생성

empty_dict = {}
# 또는
empty_dict = dict()

2. 키-값 쌍을 포함한 딕셔너리 생성

person = {
    "name": "Alice",
    "age": 30,
    "city": "New York"
}

 

 

딕셔너리 요소 접근

print(person["name"])  # 출력: Alice
print(person.get("age"))  # 출력: 30

get 메서드는 키가 존재하지 않을 때 기본 값을 반환할 수 있다.

print(person.get("address", "Address not found"))  # 출력: Address not found

 

 

딕셔너리 요소 추가 및 수정

person["email"] = "alice@example.com"  # 새로운 키-값 쌍 추가
person["age"] = 31  # 기존 키-값 쌍 수정

 

 

딕셔너리 요소 삭제

del person["city"]  # 특정 키-값 쌍 삭제
removed_value = person.pop("email")  # 특정 키-값 쌍 삭제 및 값 반환

 

 

딕셔너리 메서드
1. keys(): 모든 키 반환

keys = person.keys()
print(keys)  # dict_keys(['name', 'age'])

2. values(): 모든 값 반환

values = person.values()
print(values)  # dict_values(['Alice', 31])

3. items(): 모든 키-값 쌍 반환

items = person.items()
print(items)  # dict_items([('name', 'Alice'), ('age', 31)])

4. update(): 다른 딕셔너리로 업데이트

person.update({"age": 32, "city": "Boston"})
print(person)  # {'name': 'Alice', 'age': 32, 'city': 'Boston'}

 

 

딕셔너리 반복문

for key, value in person.items():
    print(f"{key}: {value}")

 

 

 

딕셔너리 메소드

clear()
딕셔너리의 모든 요소를 제거

person = {"name": "Alice", "age": 30, "city": "New York"}
person.clear()
print(person)  # 출력: {}

 

copy()

딕셔너리를 얕은 복사(Shallow Copy)

person = {"name": "Alice", "age": 30, "city": "New York"}
new_person = person.copy()
print(new_person)  # 출력: {'name': 'Alice', 'age': 30, 'city': 'New York'}

 

fromkeys(seq[, value])
주어진 시퀀스를 키로 하고, 모든 키의 값을 지정된 값으로 설정한 새로운 딕셔너리를 생성

keys = ["name", "age", "city"]
new_dict = dict.fromkeys(keys, "Unknown")
print(new_dict)  # 출력: {'name': 'Unknown', 'age': 'Unknown', 'city': 'Unknown'}

 

get(key[, default])
지정된 키의 값을 반환하며, 키가 존재하지 않으면 기본 값을 반환

person = {"name": "Alice", "age": 30}
age = person.get("age")
city = person.get("city", "Unknown")
print(age)  # 출력: 30
print(city)  # 출력: Unknown

 

items()
딕셔너리의 모든 키-값 쌍을 반환

person = {"name": "Alice", "age": 30}
items = person.items()
print(items)  # 출력: dict_items([('name', 'Alice'), ('age', 30)])

 

keys()
딕셔너리의 모든 키를 반환

person = {"name": "Alice", "age": 30}
keys = person.keys()
print(keys)  # 출력: dict_keys(['name', 'age'])

 

pop(key[, default])
지정된 키의 값을 반환하고 해당 키-값 쌍을 딕셔너리에서 제거

키가 존재하지 않으면 기본 값을 반환

person = {"name": "Alice", "age": 30}
age = person.pop("age")
print(age)  # 출력: 30
print(person)  # 출력: {'name': 'Alice'}

 

popitem()
마지막 키-값 쌍을 반환하고 해당 키-값 쌍을 딕셔너리에서 제거

person = {"name": "Alice", "age": 30}
item = person.popitem()
print(item)  # 출력: ('age', 30)
print(person)  # 출력: {'name': 'Alice'}

 

setdefault(key[, default])
지정된 키의 값을 반환

만약 키가 존재하지 않으면 키를 생성하고 기본 값을 설정

person = {"name": "Alice"}
age = person.setdefault("age", 30)
print(age)  # 출력: 30
print(person)  # 출력: {'name': 'Alice', 'age': 30}

 

update([other])
다른 딕셔너리나 키-값 쌍을 추가하여 딕셔너리를 업데이트

person = {"name": "Alice"}
person.update({"age": 30, "city": "New York"})
print(person)  # 출력: {'name': 'Alice', 'age': 30, 'city': 'New York'}

 

values()
딕셔너리의 모든 값을 반환

person = {"name": "Alice", "age": 30}
values = person.values()
print(values)  # 출력: dict_values(['Alice', 30])

 

 

 

정리

파이썬 딕셔너리는 매우 유용한 자료 구조로,
다양한 상황에서 효율적으로 데이터를 저장하고 조회하는 데 사용된다.

메소드들을 통해 딕셔너리를 효율적으로 관리하고 조작할 수 있으며

각 메소드는 특정 상황에서 유용하게 사용할 수 있으므로, 필요에 맞게 활용하면 된다.

728x90
반응형