230924_스터디노트

Sihyun Kim·2023년 9월 24일

자료구조

32_딕셔너리

  • 키(key)와 값(value)을 이용해서 자료를 관리
  • 키는 중복될 수 없음
  • key와 value에는 숫자, 문자(열), 논리형 뿐만 아니라 컨테이너 자료형도 가능
  • key에 immutable 값은 올 수 있지만 mutable값은 올 수 없음
    (예를 들어 tuple은 가능하지만 list는 불가능)

33_딕셔너리 조회

myInfo = {'이름' : '김땡땡', '전공' : '경영학', '학년': 3, '취미' : ['테니스', '영화 감상']}

print(myInfo)
print(myInfo['이름'])
print(myInfo['전공'])
print(myInfo['학년'])
print(myInfo['취미'])

print(myInfo.get('이름'))
print(myInfo.get('전공'))
print(myInfo.get('학년'))
print(myInfo.get('취미'))
print(myInfo['주소'])			#Key Error
print(myInfo.get('주소'))		#None

34_딕셔너리 추가

  • 딕셔너리 이름[key] = value 형태로 아이템을 추가
  • 추가 하려는 키가 이미 있다면 값이 변경됨
studentInfo = {}

studentInfo['name'] = input('이름 입력: ')
studentInfo['grade'] = input('학년 입력: ')
studentInfo['mail'] = input('메일 입력: ')
studentInfo['address'] = input('주소 입력: ')

print(studentInfo)
# studentInfo = {}
#
# studentInfo['name'] = input('이름 입력: ')
# studentInfo['grade'] = input('학년 입력: ')
# studentInfo['mail'] = input('메일 입력: ')
# studentInfo['address'] = input('주소 입력: ')
#
# print(studentInfo)

factorialDic = {}

for i in range(11):
    if i == 0:
        factorialDic[i] = 1
    else:
         factorialDic[i] = factorialDic[i-1] * i

print(factorialDic)

35_딕셔너리 수정

scores = {'kor': 88,'eng': 67,'mat': 55,'sci': 98,'his': 62}
minScore = 65
fStr = 'F(재시험)'

if scores['kor'] < minScore : scores['kor'] = fStr
if scores['eng'] < minScore : scores['eng'] = fStr
if scores['mat'] < minScore : scores['mat'] = fStr
if scores['sci'] < minScore : scores['sci'] = fStr
if scores['his'] < minScore : scores['his'] = fStr

print(scores)
myBodyInfo = {'이름': 'gildong', '몸무게': 83.0, '신장': 1.8,}
myBMI = myBodyInfo['몸무게'] / (myBodyInfo['신장'] ** 2)
myBMI = round(myBMI, 2)

print(myBodyInfo)
print(myBMI)

inputDate = int(input('경과 일수 입력: '))

myBodyInfo['몸무게'] = myBodyInfo['몸무게'] + inputDate * (-0.3)
myBodyInfo['신장'] = myBodyInfo['신장'] + inputDate * (0.001)

myBMI = myBodyInfo['몸무게'] / (myBodyInfo['신장'] ** 2)
myBMI = round(myBMI, 2)

print(myBodyInfo)
print(myBMI)
  • 풀이는 while문으로 해결함!

36_keys()와 values()

  • keys() values() items() 로 한번에 불러오기 가능
  • 리스트로 변환 가능
  • 딕셔너리는 인덱스가 존재하지 않으므로, 키를 불러와서 사용
  • for문을 이용한 딕셔너리의 조회 방법
for key in memInfo.keys():
    print(f'{key}: {memInfo[key]}')
scores = {'kor': 88,'eng': 67,'mat': 55,'sci': 98,'his': 62}
minScore = 65
fStr = 'F(재시험)'

for key in scores:
    if scores[key] < minScore:
        scores[key] = fStr

print(scores)

37_딕셔너리 삭제

  • del memInfor['메일']과 같이 아이템 삭제
  • memInfo.pop['메일']은 삭제 기능은 같으나, 삭제된 데이터 반환 가능
scores = {'score1' : 8.9, 'score2' : 8.1, 'score3' : 8.5, 'score4' : 9.8, 'score5' : 8.8}

minScore = 10; minScoreKey = ''
maxScore = 0; maxScoreKey = ''

for key in scores:
    if scores[key] < minScore:
        minScore = scores[key]
        minScoreKey = key
    elif scores[key] > maxScore:
        maxScore = scores[key]
        maxScoreKey = key

del scores[maxScoreKey]
del scores[minScoreKey]

print(scores)

38_딕셔너리 유용한 기능

  • in, not in으로 키(key) 존재 유/무 판단
  • len() 딕셔너리 길이(아이템 개수)를 알 수 있음
  • clear() 모든 아이템을 삭제
myInfo = {'이름': '김땡땡', '나이': 35, '연락처': '010-1234-5678',
          '주민등록번호': '881230-2345678', '주소': '서울'}

deleteItem = ['연락처', '주민등록번호']

for item in deleteItem:
    if item in myInfo:
        del myInfo[item]

print(myInfo)
profile
문과이과예체능통합형인재

0개의 댓글