Python - 6. 딕셔너리와 튜플

2025. 1. 19. 19:04프로그래밍 언어/Python

Python에서 딕셔너리와 튜플은 데이터 구조를 다루는 데 매우 유용한 자료형입니다. 이번 섹션에서는 딕셔너리와 튜플의 기본 사용법, 주요 메서드, 그리고 collections 모듈 활용법을 다룹니다.


6.1 딕셔너리의 기본 사용법과 메서드

딕셔너리는 키-값 쌍으로 데이터를 저장하는 자료형입니다. 각 키는 고유하며 변경할 수 없는 데이터 타입이어야 합니다.

기본 사용법

# 딕셔너리 생성
person = {
    "name": "Alice",
    "age": 25,
    "job": "Engineer"
}

# 값 접근
print(person["name"])  # Alice

# 값 추가
person["city"] = "New York"
print(person)  # {'name': 'Alice', 'age': 25, 'job': 'Engineer', 'city': 'New York'}

# 값 변경
person["age"] = 30
print(person)  # {'name': 'Alice', 'age': 30, 'job': 'Engineer', 'city': 'New York'}

# 값 삭제
del person["job"]
print(person)  # {'name': 'Alice', 'age': 30, 'city': 'New York'}

주요 메서드

  • keys(): 딕셔너리의 모든 키를 반환
  • values(): 딕셔너리의 모든 값을 반환
  • items(): 키-값 쌍을 튜플 형태로 반환
  • get(key, default): 키에 해당하는 값을 반환, 키가 없으면 기본값 반환
  • pop(key, default): 키에 해당하는 값을 반환하고 키-값 쌍 삭제
  • setdefault(key, default): 키가 없을 경우 기본값을 추가하고 값을 반환
  • update(other_dict): 다른 딕셔너리의 키-값 쌍을 추가 또는 업데이트
# 주요 메서드 예제
print(person.keys())   # dict_keys(['name', 'age', 'city'])
print(person.values()) # dict_values(['Alice', 30, 'New York'])
print(person.items())  # dict_items([('name', 'Alice'), ('age', 30), ('city', 'New York')])

# get 사용
print(person.get("job", "N/A"))  # N/A

# setdefault 사용
default_city = person.setdefault("city", "Unknown")
print(default_city)  # New York

# pop 사용
city = person.pop("city")
print(city)  # New York
print(person)  # {'name': 'Alice', 'age': 30}

딕셔너리 컴프리헨션

# 딕셔너리 컴프리헨션
squares = {x: x ** 2 for x in range(5)}
print(squares)  # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

중첩 딕셔너리

# 중첩 딕셔너리 예제
students = {
    "Alice": {"math": 90, "science": 85},
    "Bob": {"math": 75, "science": 80}
}

# 중첩 딕셔너리 접근
print(students["Alice"]["math"])  # 90

# 중첩 딕셔너리 수정
students["Bob"]["science"] = 88
print(students)

6.2 튜플의 특징과 활용

튜플은 순서가 있는 변경 불가능한 데이터 구조입니다. 리스트와 달리 튜플은 생성 후 수정할 수 없습니다.

특징

  • 소괄호 ()로 생성
  • 요소의 변경 불가
  • 저장 공간이 리스트보다 효율적
  • 딕셔너리의 키로 사용 가능

단일 요소 튜플 생성 시 주의사항

단일 요소를 가진 튜플을 생성할 때는 반드시 요소 뒤에 쉼표 ,를 추가해야 합니다.

# 단일 요소 튜플
single = (10,)
print(type(single))  # <class 'tuple'>

not_a_tuple = (10)
print(type(not_a_tuple))  # <class 'int'>

활용 예제

# 함수에서 여러 값을 반환할 때

def get_info():
    return ("Alice", 25, "Engineer")

name, age, job = get_info()
print(name, age, job)  # Alice 25 Engineer

# 딕셔너리의 키로 튜플 사용
locations = {
    (40.7128, -74.0060): "New York",
    (34.0522, -118.2437): "Los Angeles"
}
print(locations[(40.7128, -74.0060)])  # New York

튜플과 리스트의 성능 차이

튜플은 불변 속성 덕분에 리스트보다 메모리 사용량이 적고, 생성 속도가 더 빠릅니다. 데이터가 변경되지 않을 경우 튜플을 사용하는 것이 효율적입니다.

import timeit

# 리스트와 튜플 생성 시간 비교
list_time = timeit.timeit("[1, 2, 3, 4, 5]", number=1000000)
tuple_time = timeit.timeit("(1, 2, 3, 4, 5)", number=1000000)

print("List creation time:", list_time)
print("Tuple creation time:", tuple_time)

네임드 튜플의 추가 메서드

namedtuple은 _fields, _replace(), _asdict() 메서드를 제공합니다.

from collections import namedtuple

# namedtuple 정의
Point = namedtuple("Point", ["x", "y"])
point = Point(10, 20)

# _fields: 필드 이름 확인
print(point._fields)  # ('x', 'y')

# _replace: 필드 값 교체
new_point = point._replace(x=15)
print(new_point)  # Point(x=15, y=20)

# _asdict: 딕셔너리로 변환
point_dict = point._asdict()
print(point_dict)  # {'x': 10, 'y': 20}

6.3 collections 모듈 활용

Python의 collections 모듈은 고급 데이터 구조를 제공합니다.

defaultdict

키가 없을 때 기본값을 제공하는 딕셔너리입니다.

from collections import defaultdict

# defaultdict 생성
scores = defaultdict(int)
scores["Alice"] += 10
scores["Bob"] += 20
print(scores)  # defaultdict(<class 'int'>, {'Alice': 10, 'Bob': 20})

Counter

데이터의 개수를 셀 때 사용합니다.

from collections import Counter

# Counter 사용
fruits = ["apple", "banana", "apple", "cherry", "banana", "apple"]
fruit_count = Counter(fruits)
print(fruit_count)  # Counter({'apple': 3, 'banana': 2, 'cherry': 1})

# 산술 연산
counter1 = Counter(a=3, b=1)
counter2 = Counter(a=1, b=2)
print(counter1 + counter2)  # Counter({'a': 4, 'b': 3})
print(counter1 - counter2)  # Counter({'a': 2})

OrderedDict

Python 3.7부터 딕셔너리는 기본적으로 삽입 순서를 유지하지만, 이전 버전에서는 OrderedDict를 사용해야 했습니다. 여전히 명시적인 순서 제어가 필요한 경우 유용합니다.

from collections import OrderedDict

ordered = OrderedDict()
ordered["a"] = 1
ordered["b"] = 2
ordered["c"] = 3
print(ordered)  # OrderedDict([('a', 1), ('b', 2), ('c', 3)])

ChainMap

여러 딕셔너리를 하나로 묶어서 검색할 수 있습니다.

from collections import ChainMap

dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
chain = ChainMap(dict1, dict2)

print(chain["a"])  # 1
print(chain["b"])  # 2 (첫 번째 딕셔너리 값 사용)
print(chain["c"])  # 4

이번 섹션에서는 딕셔너리와 튜플의 기본 사용법과 collections 모듈의 고급 활용법을 다뤘습니다.

'프로그래밍 언어 > Python' 카테고리의 다른 글

Python - 8. 예외 처리  (0) 2025.01.19
Python - 7. 파일 입출력  (0) 2025.01.19
Python - 5. 함수  (0) 2025.01.19
Python - 4. 리스트와 문자열 심화  (0) 2025.01.19
Python - 3. 제어문  (0) 2025.01.19