[자료구조] 딕셔너리

Jimin_Note·2025년 8월 26일
0
post-thumbnail

📌 딕셔너리 (Dictionary) 🗂

  • 키(key) + 값(value) 구조
  • 선언: {키:값}
  • Key에는 immutable 자료형만 가능 (문자열, 숫자, 튜플 등)
student = {
    "이름": "홍길동",
    "전공": "컴퓨터공학",
    "메일": "hong@test.com"
}
print(student) # {'이름': '홍길동', '전공': '컴퓨터공학', '메일': 'hong@test.com'}

딕셔너리 조회

  • dict[key] → 값 조회 (없으면 KeyError)
  • dict.get(key) → 안전한 조회 (없으면 None 반환)
print(student["전공"])     # 컴퓨터공학
# print(student["주소"])   # KeyError 발생

print(student.get("주소")) # None (안전 조회)

딕셔너리 추가

  • dict[새로운키] = 값
  • 기존 키에 할당하면 값이 수정됨

👉 실습1: 학생 정보 추가

student["주소"] = "서울"
print(student) # {'이름': '홍길동', '전공': '컴퓨터공학', '메일': 'hong@test.com', '주소': '서울'}

👉 실습2: 0~10까지 각 정수의 팩토리얼 저장

factorials = {}
fact = 1
for i in range(11):
    if i == 0:
        factorials[i] = 1
    else:
        fact *= i
        factorials[i] = fact

print(factorials)
# {0:1, 1:1, 2:2, 3:6, 4:24, ... , 10:3628800}

딕셔너리 수정

  • dict[키] = 새로운값

👉 실습1: 점수가 60점 미만이면 "F(재시험)"으로 수정

scores = {"국어": 80, "영어": 45, "수학": 92, "과학": 55}

for subject in scores:
    if scores[subject] < 60:
        scores[subject] = "F(재시험)"

print(scores)
# {'국어': 80, '영어': 'F(재시험)', '수학': 92, '과학': 'F(재시험)'}

👉 실습2: 신체 정보 변화 기록 + BMI 계산

body = {"몸무게": 70.0, "신장": 1.75}  # kg, m

for day in range(30):
    body["몸무게"] -= 0.3
    body["신장"] += 0.001

bmi = body["몸무게"] / (body["신장"] ** 2)

print("30일 후 몸무게:", round(body["몸무게"], 2))
print("30일 후 신장:", round(body["신장"], 3))
print("BMI:", round(bmi, 2))

30일 후 몸무게: 61.0
30일 후 신장: 1.78
BMI: 19.25

keys()와 values()

  • dict.keys() → 전체 key 조회
  • dict.values() → 전체 value 조회
  • list()로 변환 가능
  • for문으로 순회도 가능
    👉 실습: 점수 60점 미만 항목을 keys() 순회하며 "F(재시험)" 처리
scores = {"국어": 80, "영어": 45, "수학": 92, "과학": 55}

for key in scores.keys():
    if scores[key] < 60:
        scores[key] = "F(재시험)"

print(scores)

{'국어': 80, '영어': 'F(재시험)', '수학': 92, '과학': 'F(재시험)'}

딕셔너리 유용한 기능

  • in / not in : 특정 key 존재 여부 확인
  • len(dict) : 아이템 개수 확인
  • dict.clear() : 모든 아이템 삭제
person = {
    "이름": "홍길동",
    "메일": "hong@test.com",
    "연락처": "010-1234-5678",
    "주민등록번호": "900101-1234567"
}

# key 존재 여부 확인 후 삭제
if "연락처" in person:
    del person["연락처"]

if "주민등록번호" in person:
    del person["주민등록번호"]

print(person)
# {'이름': '홍길동', '메일': 'hong@test.com'}

# dict 길이 확인
print(len(person))  # 2

# 전체 삭제
person.clear()
print(person)  # {}

{'이름': '홍길동', '메일': 'hong@test.com'}
2
{}

profile
Hello. I'm jimin:)

0개의 댓글