{키:값}
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
dict.keys()
→ 전체 key 조회dict.values()
→ 전체 value 조회list()
로 변환 가능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
{}