실버를 위한 코딩/파이썬 연습

[파이썬 연습] 딕셔너리(Dictionary)란?

forSilver 2024. 11. 27. 05:10
반응형

딕셔너리(Dictionary)란?

파이썬의 딕셔너리(Dictionary)는 키(key)-값(value) 쌍으로 이루어진 자료형입니다. 데이터를 이름으로 매핑하여 저장하기 때문에 빠르고 효율적인 데이터 검색이 가능합니다. 딕셔너리는 {} 중괄호를 사용해 선언합니다.


딕셔너리의 주요 특징

  • 키-값 쌍으로 구성:
    • 키: 고유하며 불변(immutable)해야 함 (문자열, 숫자, 튜플 등 가능).
    • 값: 변경 가능한(mutable) 모든 자료형 사용 가능.
  • 순서 유지 (파이썬 3.7 이상):
    딕셔너리는 삽입된 순서를 유지합니다.
  • 중복 키 불허:
    동일한 키가 여러 개 존재하면, 마지막에 정의된 키-값 쌍이 유지됩니다.
  • 변경 가능(Mutable):
    딕셔너리는 추가, 삭제, 수정 가능.

딕셔너리 생성 방법

# 빈 딕셔너리 생성
empty_dict = {}

# 키-값 쌍으로 딕셔너리 생성
person = {"name": "Alice", "age": 25, "city": "New York"}

# dict() 함수 사용
person2 = dict(name="Bob", age=30, city="Los Angeles")

딕셔너리 생성


딕셔너리 주요 연산 및 메서드

1. 요소 접근

person = {"name": "Alice", "age": 25}

print(person["name"])  # Alice
print(person.get("age"))  # 25
print(person.get("gender", "Not Specified"))  # 키가 없을 경우 기본값 반환

키가 없으면 기본값 반환

2. 요소 추가 및 수정

person = {"name": "Alice"}

# 새로운 키-값 쌍 추가
person["age"] = 25

# 기존 키 수정
person["name"] = "Bob"

print(person)  # {'name': 'Bob', 'age': 25}

3. 요소 삭제

person = {"name": "Alice", "age": 25}

# 특정 키 삭제
del person["age"]

# pop()으로 삭제 후 값 반환
name = person.pop("name")
print(name)  # Alice

4. 모든 요소 삭제

person.clear()  # 딕셔너리 초기화

딕셔너리 메서드

메서드 설명
keys() 모든 키를 반환
values() 모든 값을 반환
items() 모든 키-값 쌍을 반환 (튜플 형태)
update(other_dict) 다른 딕셔너리의 키-값 쌍을 추가 또는 갱신
pop(key[, default]) 지정된 키의 값을 반환하고 삭제 (없으면 기본값 반환)
get(key[, default]) 키에 대응하는 값을 반환 (없으면 기본값 반환)

딕셔너리 순회

키 순회

person = {"name": "Alice", "age": 25}
for key in person:
    print(key)  # 'name', 'age'

값 순회

for value in person.values():
    print(value)  # 'Alice', 25

키-값 쌍 순회

for key, value in person.items():
    print(f"{key}: {value}")  # 'name: Alice', 'age: 25'

활용 예시

1. 단어 빈도 계산

text = "apple banana apple orange banana apple"
word_count = {}

for word in text.split():
    word_count[word] = word_count.get(word, 0) + 1

print(word_count)  # {'apple': 3, 'banana': 2, 'orange': 1}

2. 딕셔너리 기반 학생 점수 관리

scores = {"Alice": 85, "Bob": 90, "Charlie": 78}

# 점수 추가
scores["Diana"] = 92

# 특정 학생 점수 출력
print(scores.get("Alice", "No score available"))  # 85

딕셔너리와 관련된 유용한 기능

1. 딕셔너리 변환

  • 딕셔너리를 리스트나 다른 형태로 변환할 수 있습니다.
    # 키만 리스트로 변환
    keys_list = list(person.keys())
    

값만 리스트로 변환

values_list = list(person.values())

(키, 값) 튜플 목록 생성

items_list = list(person.items())

dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}

dict1.update(dict2)  # {'a': 1, 'b': 3, 'c': 4}

실습 과제

1. 주어진 딕셔너리에서 모든 키와 값을 출력하세요.

fruits = {"apple": 3, "banana": 5, "cherry": 7}

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

2. 학생 이름과 점수를 딕셔너리로 저장한 뒤, 평균 점수를 계산하는 프로그램을 작성하세요.

scores = {"Alice": 85, "Bob": 90, "Charlie": 78}

average_score = sum(scores.values()) / len(scores)
print(f"Average score: {average_score:.2f}")

3. 텍스트에서 각 단어의 빈도를 계산해 딕셔너리로 저장하는 코드를 작성하세요.

text = "hello world hello python world python python"
word_count = {}

for word in text.split():
    word_count[word] = word_count.get(word, 0) + 1

print(word_count)

4. update() 메서드를 사용하여 두 딕셔너리를 합치고 결과를 출력하세요.

dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}

dict1.update(dict2)
print(dict1)