← 파이썬 강의 목록으로
🌱
기초 (Basic)
dict · key/value · get/items · set · 합/교/차

7주차 — 딕셔너리와 집합

키로 값을 빠르게 찾는 딕셔너리, 자주 쓰는 메서드(get, items, in), 중복 없는 집합과 합/교/차/대칭차 연산, 그리고 자료구조 선택 기준을 익힙니다.

dictsetkey-valuein
소요 시간
2시간
난이도
📊 완전 초보
선수 조건
🎯 6주차
결과물
딕셔너리로 데이터 모델링 + 집합 연산으로 중복 제거

이 강의에서 배우는 것

  • 1딕셔너리 생성·키 접근·수정
  • 2자주 쓰는 메서드 (get, items, keys)
  • 3집합(set) 연산 (합집합/교집합/차집합)
  • 4자료구조 선택 기준

1. 딕셔너리란

키(key) → 값(value) 의 매핑. 순서 X (3.7+ 부터는 입력 순서 유지). 중괄호 {...}.

python
student = {"name": "홍길동", "age": 20, "major": "CS"}

print(student["name"])      # 홍길동
student["age"] = 21         # 수정
student["email"] = "..."    # 추가
del student["major"]        # 삭제

키는 보통 문자열 또는 숫자, 값은 어떤 타입이든 가능.

2. 자주 쓰는 메서드

python
d = {"a": 1, "b": 2, "c": 3}

print(d.keys())     # dict_keys(['a', 'b', 'c'])
print(d.values())   # dict_values([1, 2, 3])
print(d.items())    # dict_items([('a', 1), ...])

# get: 안전하게 조회 (키 없어도 에러 X)
print(d.get("z"))            # None
print(d.get("z", "기본값"))  # 기본값

# in: 키 존재 확인
print("a" in d)     # True

3. 딕셔너리 순회

python
for key in d:                    # 키만
    print(key)

for key, value in d.items():     # 키-값 동시
    print(f"{key} = {value}")

4. 집합 (set)

중복 없는 원소의 모음. 순서 X. 중괄호 {...} (단, 빈 set은 set()).

python
fruits = {"사과", "바나나", "포도"}
fruits.add("딸기")
fruits.discard("바나나")    # 없으면 무시
print(len(fruits))

# 중복 자동 제거
nums = [1, 2, 2, 3, 3, 3]
unique = set(nums)         # {1, 2, 3}

5. 집합 연산

python
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

print(a | b)    # 합집합 {1,2,3,4,5,6}
print(a & b)    # 교집합 {3,4}
print(a - b)    # 차집합 {1,2}
print(a ^ b)    # 대칭차 {1,2,5,6}

6. 자료구조 선택 기준

상황선택
순서 중요, 인덱스로 접근리스트
변경 불필요, 빠르게튜플
키로 값 조회딕셔너리
중복 제거, 멤버십 검사집합

7. 자주 하는 실수

1) 존재하지 않는 키 접근

python
d = {"a": 1}
print(d["z"])    # KeyError

→ d.get("z") 사용 또는 if "z" in d:

2) 빈 set을 {}로 만들기

python
s = {}    # 빈 딕셔너리!
s = set() # 빈 set

3) set에 리스트 넣기

python
{[1, 2]}    # TypeError: unhashable type: 'list'
{(1, 2)}    # 튜플은 OK

4) 딕셔너리 순회 중 수정

python
for k in d:
    del d[k]   # RuntimeError

→ 키 목록을 미리 복사: for k in list(d):

8. FAQ

Q1. 딕셔너리의 키 중복 시?

마지막 값으로 덮어씀. 키는 유일해야 함.

Q2. 딕셔너리는 정렬되나요?

Python 3.7+ 부터 입력 순서 유지. 정렬은 sorted(d.items()).

Q3. 집합과 딕셔너리 둘 다 {} 인데 어떻게 구분?

: 가 있으면 딕셔너리, 없으면 집합. {1, 2} = set, {1: "a"} = dict.

💻 예제 (examples)

실제로 실행해 결과를 확인할 수 있는 예제 코드입니다.

01_dict_basic.py딕셔너리 생성/수정/삭제
CODE
student = {"name": "홍길동", "age": 20, "major": "CS"}
print(student["name"])

student["age"] = 21
student["email"] = "h@example.com"
del student["major"]
print(student)
▶ 실행 결과
홍길동
{'name': '홍길동', 'age': 21, 'email': 'h@example.com'}
02_dict_methods.pyget, items, in
CODE
d = {"a": 1, "b": 2, "c": 3}

print(d.keys())
print(d.values())
print(d.items())

print(d.get("z"))             # None
print(d.get("z", "기본값"))   # 기본값
print("a" in d)               # True

for k, v in d.items():
    print(f"{k} = {v}")
▶ 실행 결과
dict_keys(['a', 'b', 'c'])
dict_values([1, 2, 3])
dict_items([('a', 1), ('b', 2), ('c', 3)])
None
기본값
True
a = 1
b = 2
c = 3
03_set.py집합 생성과 4가지 연산
CODE
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

print(a | b)    # 합집합
print(a & b)    # 교집합
print(a - b)    # 차집합
print(a ^ b)    # 대칭차

# 리스트 중복 제거
nums = [1, 2, 2, 3, 3, 3]
print(list(set(nums)))
▶ 실행 결과
{1, 2, 3, 4, 5, 6}
{3, 4}
{1, 2}
{1, 2, 5, 6}
[1, 2, 3]
04_word_count.py단어 빈도 카운트 (딕셔너리 활용)
CODE
text = "apple banana apple cherry banana apple"
words = text.split()

count = {}
for w in words:
    count[w] = count.get(w, 0) + 1

print(count)
▶ 실행 결과
{'apple': 3, 'banana': 2, 'cherry': 1}

📝 과제 (exercises)

직접 풀어보고, 막힐 때 정답을 펼쳐 비교해보세요.

과제 1

연락처 프로그램

목표: 이름으로 전화번호를 저장/조회/삭제하는 CLI.

요구사항
  • 데이터: {"이름": "전화번호"} 딕셔너리
  • 명령: add, find, del, list, quit
  • find 시 없는 이름은 "찾을 수 없습니다"
입출력 예시
명령: add
이름: 홍길동
전화: 010-1234-5678
추가됨

명령: find
이름: 홍길동
홍길동: 010-1234-5678

명령: list
1. 홍길동: 010-1234-5678
정답 코드 펼치기 / 접기
SOLUTION
contacts = {}

while True:
    cmd = input("명령(add/find/del/list/quit): ")
    if cmd == "quit":
        break
    elif cmd == "add":
        name = input("이름: ")
        phone = input("전화: ")
        contacts[name] = phone
        print("추가됨")
    elif cmd == "find":
        name = input("이름: ")
        if name in contacts:
            print(f"{name}: {contacts[name]}")
        else:
            print("찾을 수 없습니다")
    elif cmd == "del":
        name = input("이름: ")
        if name in contacts:
            del contacts[name]
            print("삭제됨")
        else:
            print("찾을 수 없습니다")
    elif cmd == "list":
        for i, (name, phone) in enumerate(contacts.items(), start=1):
            print(f"{i}. {name}: {phone}")
▶ 실행 결과
명령(add/find/del/list/quit): add
이름: 홍길동
전화: 010-1234-5678
추가됨
명령(add/find/del/list/quit): list
1. 홍길동: 010-1234-5678
명령(add/find/del/list/quit): quit
과제 2

단어 빈도 Top 3

목표: 긴 문장에서 가장 많이 등장한 단어 3개를 출력한다.

요구사항
  • 입력은 코드 안에 변수로 (긴 문장)
  • 단어는 공백으로 분리
  • 빈도 내림차순으로 정렬, 상위 3개
💡 힌트

sorted(d.items(), key=lambda x: x[1], reverse=True) 로 값 기준 정렬

입출력 예시
1. apple: 5번
2. banana: 3번
3. cherry: 2번
정답 코드 펼치기 / 접기
SOLUTION
text = "apple banana apple cherry banana apple cherry apple banana apple"

words = text.split()
count = {}
for w in words:
    count[w] = count.get(w, 0) + 1

top3 = sorted(count.items(), key=lambda x: x[1], reverse=True)[:3]
for i, (word, n) in enumerate(top3, start=1):
    print(f"{i}. {word}: {n}번")
▶ 실행 결과
1. apple: 5번
2. banana: 3번
3. cherry: 2번
과제 3

중복 제거 (순서 유지)

목표: 리스트에서 중복을 제거하되 원래 입력 순서를 유지한다.

요구사항
  • 입력: ["a", "b", "a", "c", "b", "d"]
  • 출력: ["a", "b", "c", "d"]
  • set() 만으로는 순서가 깨질 수 있음 → 딕셔너리 활용
💡 힌트

dict.fromkeys(리스트) 활용

정답 코드 펼치기 / 접기
SOLUTION
items = ["a", "b", "a", "c", "b", "d"]

# 방법 1: dict.fromkeys (가장 간결, 순서 유지)
result = list(dict.fromkeys(items))
print(result)

# 방법 2: 직접 순회
seen = set()
result2 = []
for x in items:
    if x not in seen:
        seen.add(x)
        result2.append(x)
print(result2)
▶ 실행 결과
['a', 'b', 'c', 'd']
['a', 'b', 'c', 'd']
예제 코드 / 강의 자료

전체 강의 자료와 예제 코드는 GitHub에서 자유롭게 받아볼 수 있습니다.

GitHub에서 보기 ↗