WeniVooks

검색

Cursor 톺아보기 with Python

딕셔너리 마스터하기 - 키-값으로 데이터 관리

5.1 딕셔너리 마스터하기 - 키-값으로 데이터 관리

🎯 오늘 배울 내용

리스트는 순서대로 데이터를 저장했다면, 딕셔너리이름(키)과 값을 짝지어서 저장하는 방법을 배워보겠습니다!

📚 이전 내용 간단 요약

Chapter 2에서 배운 기초 개념:

# 리스트로 데이터 관리 (Chapter 2.2)
students = ["김철수", "이영희", "박민수"]
scores = [85, 92, 78]
 
# for문으로 출력
for i in range(len(students)):
    print(f"{students[i]}: {scores[i]}점")
# 리스트로 데이터 관리 (Chapter 2.2)
students = ["김철수", "이영희", "박민수"]
scores = [85, 92, 78]
 
# for문으로 출력
for i in range(len(students)):
    print(f"{students[i]}: {scores[i]}점")

문제점: 데이터가 많아지면 관리가 복잡해집니다 😰

💡 딕셔너리의 필요성
상황: 학생 정보를 더 체계적으로 관리하고 싶다면?

Chat에 질문:

리스트 대신 이름으로 바로 점수를 찾을 수 있는 
더 편한 방법이 있나요?
리스트 대신 이름으로 바로 점수를 찾을 수 있는 
더 편한 방법이 있나요?

AI의 답변: 딕셔너리 소개

# 리스트 방식 (불편함)
students = ["김철수", "이영희", "박민수"]
scores = [85, 92, 78]
 
# 딕셔너리 방식 (편함!)
student_scores = {
    "김철수": 85,
    "이영희": 92,
    "박민수": 78
}
 
# 이름으로 바로 점수 찾기
print(student_scores["김철수"])  # 85
# 리스트 방식 (불편함)
students = ["김철수", "이영희", "박민수"]
scores = [85, 92, 78]
 
# 딕셔너리 방식 (편함!)
student_scores = {
    "김철수": 85,
    "이영희": 92,
    "박민수": 78
}
 
# 이름으로 바로 점수 찾기
print(student_scores["김철수"])  # 85
🔍 PART 1: 딕셔너리 기초
딕셔너리 만들기

Chat에 요청:

딕셔너리 만드는 방법과 기본 사용법을 알려주세요.
딕셔너리 만드는 방법과 기본 사용법을 알려주세요.

기본 문법:

# 1. 빈 딕셔너리 만들기
my_dict = {}
 
# 2. 데이터와 함께 만들기
student_info = {
    "이름": "김코딩",
    "나이": 20,
    "전공": "컴퓨터공학"
}
 
# 3. 값 가져오기
print(student_info["이름"])    # 김코딩
print(student_info["나이"])    # 20
 
# 4. 새로운 데이터 추가하기
student_info["학년"] = 2
print(student_info)
 
# 5. 데이터 수정하기
student_info["나이"] = 21
print(student_info)
# 1. 빈 딕셔너리 만들기
my_dict = {}
 
# 2. 데이터와 함께 만들기
student_info = {
    "이름": "김코딩",
    "나이": 20,
    "전공": "컴퓨터공학"
}
 
# 3. 값 가져오기
print(student_info["이름"])    # 김코딩
print(student_info["나이"])    # 20
 
# 4. 새로운 데이터 추가하기
student_info["학년"] = 2
print(student_info)
 
# 5. 데이터 수정하기
student_info["나이"] = 21
print(student_info)
🎯 실습 1: 나만의 프로필 딕셔너리
print("=== 나만의 프로필 만들기 ===")
 
# 내 정보 딕셔너리
my_profile = {
    "이름": "파이썬초보",
    "나이": 25,
    "취미": "코딩",
    "좋아하는_음식": "피자"
}
 
print("내 프로필:")
print(f"이름: {my_profile['이름']}")
print(f"나이: {my_profile['나이']}세")
print(f"취미: {my_profile['취미']}")
print(f"좋아하는 음식: {my_profile['좋아하는_음식']}")
 
# 새로운 정보 추가
my_profile["거주지"] = "서울"
my_profile["목표"] = "Python 마스터"
 
print("\n업데이트된 프로필:")
for key in my_profile:
    print(f"{key}: {my_profile[key]}")
print("=== 나만의 프로필 만들기 ===")
 
# 내 정보 딕셔너리
my_profile = {
    "이름": "파이썬초보",
    "나이": 25,
    "취미": "코딩",
    "좋아하는_음식": "피자"
}
 
print("내 프로필:")
print(f"이름: {my_profile['이름']}")
print(f"나이: {my_profile['나이']}세")
print(f"취미: {my_profile['취미']}")
print(f"좋아하는 음식: {my_profile['좋아하는_음식']}")
 
# 새로운 정보 추가
my_profile["거주지"] = "서울"
my_profile["목표"] = "Python 마스터"
 
print("\n업데이트된 프로필:")
for key in my_profile:
    print(f"{key}: {my_profile[key]}")
🔍 PART 2: 딕셔너리로 학생 관리하기
🎯 실습 2: 학생 성적 관리 시스템

Chat에 요청:

딕셔너리를 사용해서 여러 학생의 정보를 
체계적으로 관리하는 프로그램을 만들어주세요.
딕셔너리를 사용해서 여러 학생의 정보를 
체계적으로 관리하는 프로그램을 만들어주세요.
print("=== 학생 성적 관리 시스템 ===")
 
# 학생들의 성적 정보
class_scores = {
    "김철수": 85,
    "이영희": 92,
    "박민수": 78,
    "최지영": 95,
    "정수호": 88
}
 
print("📚 우리 반 성적:")
for student in class_scores:
    score = class_scores[student]
    print(f"{student}: {score}점")
 
# 평균 계산
total = 0
student_count = 0
 
for student in class_scores:
    total += class_scores[student]
    student_count += 1
 
average = total / student_count
print(f"\n📊 반 평균: {average:.1f}점")
 
# 최고점 학생 찾기
highest_score = 0
best_student = ""
 
for student in class_scores:
    if class_scores[student] > highest_score:
        highest_score = class_scores[student]
        best_student = student
 
print(f"🏆 최고점: {best_student} ({highest_score}점)")
 
# 특정 점수 이상 학생들
print(f"\n🌟 90점 이상 학생들:")
for student in class_scores:
    if class_scores[student] >= 90:
        print(f"👏 {student}: {class_scores[student]}점")
print("=== 학생 성적 관리 시스템 ===")
 
# 학생들의 성적 정보
class_scores = {
    "김철수": 85,
    "이영희": 92,
    "박민수": 78,
    "최지영": 95,
    "정수호": 88
}
 
print("📚 우리 반 성적:")
for student in class_scores:
    score = class_scores[student]
    print(f"{student}: {score}점")
 
# 평균 계산
total = 0
student_count = 0
 
for student in class_scores:
    total += class_scores[student]
    student_count += 1
 
average = total / student_count
print(f"\n📊 반 평균: {average:.1f}점")
 
# 최고점 학생 찾기
highest_score = 0
best_student = ""
 
for student in class_scores:
    if class_scores[student] > highest_score:
        highest_score = class_scores[student]
        best_student = student
 
print(f"🏆 최고점: {best_student} ({highest_score}점)")
 
# 특정 점수 이상 학생들
print(f"\n🌟 90점 이상 학생들:")
for student in class_scores:
    if class_scores[student] >= 90:
        print(f"👏 {student}: {class_scores[student]}점")
🔍 PART 3: 딕셔너리 안전하게 사용하기
에러 예방하기

Chat에 질문:

딕셔너리에서 없는 키를 찾을 때 
에러가 나지 않게 하는 방법이 있나요?
딕셔너리에서 없는 키를 찾을 때 
에러가 나지 않게 하는 방법이 있나요?
# 학생 성적 딕셔너리
scores = {
    "김철수": 85,
    "이영희": 92,
    "박민수": 78
}
 
# 안전한 방법 1: 먼저 확인하기
search_name = input("찾을 학생 이름: ")
 
if search_name in scores:
    print(f"{search_name}: {scores[search_name]}점")
else:
    print(f"{search_name} 학생을 찾을 수 없습니다.")
 
# 안전한 방법 2: .get() 사용하기
result = scores.get(search_name, "없음")
print(f"검색 결과: {result}")
 
# 기본값 설정
score = scores.get(search_name, 0)
if score > 0:
    print(f"점수: {score}점")
else:
    print("등록되지 않은 학생입니다.")
# 학생 성적 딕셔너리
scores = {
    "김철수": 85,
    "이영희": 92,
    "박민수": 78
}
 
# 안전한 방법 1: 먼저 확인하기
search_name = input("찾을 학생 이름: ")
 
if search_name in scores:
    print(f"{search_name}: {scores[search_name]}점")
else:
    print(f"{search_name} 학생을 찾을 수 없습니다.")
 
# 안전한 방법 2: .get() 사용하기
result = scores.get(search_name, "없음")
print(f"검색 결과: {result}")
 
# 기본값 설정
score = scores.get(search_name, 0)
if score > 0:
    print(f"점수: {score}점")
else:
    print("등록되지 않은 학생입니다.")
🔍 PART 4: 복잡한 딕셔너리 다루기
🎯 실습 3: 학생 종합 정보 관리
print("=== 학생 종합 정보 관리 시스템 ===")
 
# 각 학생의 상세 정보
students_data = {
    "김철수": {
        "나이": 20,
        "전공": "컴퓨터공학",
        "성적": [85, 90, 88],
        "출석률": 95
    },
    "이영희": {
        "나이": 19,
        "전공": "수학과",
        "성적": [92, 95, 89],
        "출석률": 98
    },
    "박민수": {
        "나이": 21,
        "전공": "물리학과",
        "성적": [78, 82, 85],
        "출석률": 90
    }
}
 
# 모든 학생 정보 출력
for name in students_data:
    student = students_data[name]
    
    print(f"\n📋 {name}님 정보:")
    print(f"  나이: {student['나이']}세")
    print(f"  전공: {student['전공']}")
    print(f"  출석률: {student['출석률']}%")
    
    # 성적 평균 계산
    scores = student['성적']
    total = 0
    for score in scores:
        total += score
    average = total / len(scores)
    
    print(f"  성적 평균: {average:.1f}점")
 
# 우수 학생 찾기 (평균 90점 이상)
print("\n🌟 우수 학생 (평균 90점 이상):")
for name in students_data:
    scores = students_data[name]['성적']
    total = 0
    for score in scores:
        total += score
    average = total / len(scores)
    
    if average >= 90:
        print(f"👏 {name}: {average:.1f}점")
print("=== 학생 종합 정보 관리 시스템 ===")
 
# 각 학생의 상세 정보
students_data = {
    "김철수": {
        "나이": 20,
        "전공": "컴퓨터공학",
        "성적": [85, 90, 88],
        "출석률": 95
    },
    "이영희": {
        "나이": 19,
        "전공": "수학과",
        "성적": [92, 95, 89],
        "출석률": 98
    },
    "박민수": {
        "나이": 21,
        "전공": "물리학과",
        "성적": [78, 82, 85],
        "출석률": 90
    }
}
 
# 모든 학생 정보 출력
for name in students_data:
    student = students_data[name]
    
    print(f"\n📋 {name}님 정보:")
    print(f"  나이: {student['나이']}세")
    print(f"  전공: {student['전공']}")
    print(f"  출석률: {student['출석률']}%")
    
    # 성적 평균 계산
    scores = student['성적']
    total = 0
    for score in scores:
        total += score
    average = total / len(scores)
    
    print(f"  성적 평균: {average:.1f}점")
 
# 우수 학생 찾기 (평균 90점 이상)
print("\n🌟 우수 학생 (평균 90점 이상):")
for name in students_data:
    scores = students_data[name]['성적']
    total = 0
    for score in scores:
        total += score
    average = total / len(scores)
    
    if average >= 90:
        print(f"👏 {name}: {average:.1f}점")
🔍 PART 5: 딕셔너리를 활용한 게임 데이터
🎯 실습 4: RPG 캐릭터 관리

Chat에 요청:

RPG 게임의 캐릭터 정보를 딕셔너리로 관리하는 
시스템을 만들어주세요.
RPG 게임의 캐릭터 정보를 딕셔너리로 관리하는 
시스템을 만들어주세요.
print("⚔️ RPG 캐릭터 관리 시스템")
 
# 캐릭터 정보
hero = {
    "이름": "용사",
    "직업": "전사",
    "레벨": 1,
    "HP": 100,
    "MP": 50,
    "경험치": 0,
    "골드": 100,
    "장비": {
        "무기": "나무검",
        "방어구": "천옷",
        "악세서리": "없음"
    },
    "인벤토리": ["체력포션", "마나포션", "빵"]
}
 
# 캐릭터 상태 출력
print(f"\n👤 캐릭터 정보")
print(f"이름: {hero['이름']} ({hero['직업']})")
print(f"레벨: {hero['레벨']}")
print(f"HP: {hero['HP']} / MP: {hero['MP']}")
print(f"경험치: {hero['경험치']} / 골드: {hero['골드']}G")
 
print(f"\n⚔️ 장착 장비:")
equipment = hero['장비']
for item_type in equipment:
    print(f"{item_type}: {equipment[item_type]}")
 
print(f"\n🎒 인벤토리:")
inventory = hero['인벤토리']
for i in range(len(inventory)):
    print(f"{i+1}. {inventory[i]}")
 
# 레벨업 시뮬레이션
print(f"\n📈 레벨업!")
hero['레벨'] += 1
hero['HP'] += 20
hero['MP'] += 10
hero['경험치'] = 0
 
print(f"레벨이 {hero['레벨']}로 상승했습니다!")
print(f"HP: {hero['HP']}, MP: {hero['MP']}")
 
# 아이템 획득
new_item = "마법검"
hero['장비']['무기'] = new_item
print(f"\n🎁 새로운 무기 '{new_item}'를 획득했습니다!")
print("⚔️ RPG 캐릭터 관리 시스템")
 
# 캐릭터 정보
hero = {
    "이름": "용사",
    "직업": "전사",
    "레벨": 1,
    "HP": 100,
    "MP": 50,
    "경험치": 0,
    "골드": 100,
    "장비": {
        "무기": "나무검",
        "방어구": "천옷",
        "악세서리": "없음"
    },
    "인벤토리": ["체력포션", "마나포션", "빵"]
}
 
# 캐릭터 상태 출력
print(f"\n👤 캐릭터 정보")
print(f"이름: {hero['이름']} ({hero['직업']})")
print(f"레벨: {hero['레벨']}")
print(f"HP: {hero['HP']} / MP: {hero['MP']}")
print(f"경험치: {hero['경험치']} / 골드: {hero['골드']}G")
 
print(f"\n⚔️ 장착 장비:")
equipment = hero['장비']
for item_type in equipment:
    print(f"{item_type}: {equipment[item_type]}")
 
print(f"\n🎒 인벤토리:")
inventory = hero['인벤토리']
for i in range(len(inventory)):
    print(f"{i+1}. {inventory[i]}")
 
# 레벨업 시뮬레이션
print(f"\n📈 레벨업!")
hero['레벨'] += 1
hero['HP'] += 20
hero['MP'] += 10
hero['경험치'] = 0
 
print(f"레벨이 {hero['레벨']}로 상승했습니다!")
print(f"HP: {hero['HP']}, MP: {hero['MP']}")
 
# 아이템 획득
new_item = "마법검"
hero['장비']['무기'] = new_item
print(f"\n🎁 새로운 무기 '{new_item}'를 획득했습니다!")
💪 종합 실습: 개인 가계부 만들기

🎯 최종 미션: 딕셔너리로 가계부 프로그램

print("💰 개인 가계부 관리 프로그램")
print("=" * 40)
 
# 가계부 데이터
account_book = {
    "수입": {
        "용돈": 50000,
        "아르바이트": 200000,
        "기타": 30000
    },
    "지출": {
        "식비": 150000,
        "교통비": 50000,
        "문화생활": 80000,
        "기타": 40000
    }
}
 
# 수입 총액 계산
print("📈 이번 달 수입:")
total_income = 0
for category in account_book["수입"]:
    amount = account_book["수입"][category]
    print(f"  {category}: {amount:,}원")
    total_income += amount
 
print(f"수입 총액: {total_income:,}원")
 
# 지출 총액 계산
print(f"\n📉 이번 달 지출:")
total_expense = 0
for category in account_book["지출"]:
    amount = account_book["지출"][category]
    print(f"  {category}: {amount:,}원")
    total_expense += amount
 
print(f"지출 총액: {total_expense:,}원")
 
# 잔액 계산
balance = total_income - total_expense
print(f"\n💳 잔액: {balance:,}원")
 
if balance > 0:
    print("🎉 이번 달은 흑자입니다!")
elif balance == 0:
    print("😐 수입과 지출이 같습니다.")
else:
    print("😰 이번 달은 적자입니다. 지출을 줄여보세요!")
 
# 가장 큰 지출 항목 찾기
max_expense = 0
max_category = ""
 
for category in account_book["지출"]:
    amount = account_book["지출"][category]
    if amount > max_expense:
        max_expense = amount
        max_category = category
 
print(f"\n📊 가장 큰 지출: {max_category} ({max_expense:,}원)")
print("💰 개인 가계부 관리 프로그램")
print("=" * 40)
 
# 가계부 데이터
account_book = {
    "수입": {
        "용돈": 50000,
        "아르바이트": 200000,
        "기타": 30000
    },
    "지출": {
        "식비": 150000,
        "교통비": 50000,
        "문화생활": 80000,
        "기타": 40000
    }
}
 
# 수입 총액 계산
print("📈 이번 달 수입:")
total_income = 0
for category in account_book["수입"]:
    amount = account_book["수입"][category]
    print(f"  {category}: {amount:,}원")
    total_income += amount
 
print(f"수입 총액: {total_income:,}원")
 
# 지출 총액 계산
print(f"\n📉 이번 달 지출:")
total_expense = 0
for category in account_book["지출"]:
    amount = account_book["지출"][category]
    print(f"  {category}: {amount:,}원")
    total_expense += amount
 
print(f"지출 총액: {total_expense:,}원")
 
# 잔액 계산
balance = total_income - total_expense
print(f"\n💳 잔액: {balance:,}원")
 
if balance > 0:
    print("🎉 이번 달은 흑자입니다!")
elif balance == 0:
    print("😐 수입과 지출이 같습니다.")
else:
    print("😰 이번 달은 적자입니다. 지출을 줄여보세요!")
 
# 가장 큰 지출 항목 찾기
max_expense = 0
max_category = ""
 
for category in account_book["지출"]:
    amount = account_book["지출"][category]
    if amount > max_expense:
        max_expense = amount
        max_category = category
 
print(f"\n📊 가장 큰 지출: {max_category} ({max_expense:,}원)")
🌟 이번 챕터에서 배운 것
  1. 딕셔너리 기본 문법 ({}, 키-값 쌍)
  2. 데이터 추가/수정/조회 방법
  3. 딕셔너리 순회하기 (for key in dict)
  4. 안전한 접근법 (in 연산자, .get() 메서드)
  5. 복잡한 데이터 구조 (딕셔너리 안에 리스트, 딕셔너리)

💡 핵심 포인트:

  • 딕셔너리는 이름(키)으로 데이터를 찾을 때 매우 유용
  • 리스트보다 직관적이고 관리하기 쉬움
  • 게임, 가계부, 학생 관리 등 실생활 데이터에 최적

🚀 다음 챕터 예고: Chapter 5.2에서는 문자열과 리스트의 고급 메서드들을 배워보겠습니다!

{"packages":["numpy","pandas","matplotlib","lxml"]}
5장 Chapter 055.2 문자열과 리스트 고급 활용 - 실전 메서드들