자료구조_'딕셔너리'의 모든 것

jaam._.mini·2023년 11월 18일
0

📒Python 기초 수학

목록 보기
37/46

자료구조의 마지막!
[딕셔너리] 에 대해서 자세히 알아보자!


1. 딕셔너리 란?

Key와 Value를 이용해서 자료를 관리한다

  • [리스트]는 데이터를 줄세우고 번호를 부여(인덱스)한다

  • ⭐[딕셔너리]는 번호(인덱스)가 존재 하지 않아, 직접 key & value를 정해줘야 한다

  • [리스트/튜플]은 중복이 가능

  • ⭐[딕셔너리]의 key는 절.대 중복되면 안됨

  • ⭐key에 immutable한 값만 올 수 있다 = key는 변경이 불가능한 data만 올 수 있다 (리스트는 올 수 없음, 튜플은 변경이 불가능하즘로 올 수 있음)

  • ⭐반면 value는 변경이 가능해 모든 data가 올 수 있다

  • ex.
students = {'s1':'H', 's2':'P', 's3':'K', 's4':['G', 'W']}
print(type(students))
print(students)

<class 'dict'>
{'s1': 'H', 's2': 'P', 's3': 'K', 's4': ['G', 'W']}

2. 조회

(1) key, value 이용

  • print('students[\'s1\'] : {}'.format(딕셔너리 이름 명시[ key값 ])) :
students = {'s1':'H', 's2':'P', 's3':'K', 's4':['G', 'W']}

print(students['s1'])
print(students['s4'][0])
print(students['s4'][1])

H
G
W

(2) get(key) 이용

  • 존재하지 않는 키를 이용한 조회 시 erroe가 발생한다
KeyError: 's5'
  • 반면 get()은 key가 없어도 에러가 발생하지 않는다
students = {'s1':'H', 's2':'P', 's3':'K', 's4':['G', 'W']}
print(students.get('s5'))


None


3. item 추가

'딕셔너리 이름[키;key] = 값;value

studentInfo = {}

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

print(f'studentInfo : {studentInfo}')

이름 입력: Jaam._.mini
학년 입력: 3
메일 입력: jamjam@naver.com
주소 입력: korea
studentInfo : {'name': 'Jaam._.mini', 'grade': '3', 'mail': 'jamjam@naver.com', 'addr': 'korea'}

🏷️실습

Q> 0부터 10까지의 각각의 정수에 대한 팩토리얼을 딕셔너리에 추가

  • if i == 0: : i 가 0일 때
  • factorialDic[i] = 1 : 0팩토리얼은 1로 정하자
  • for j in range(1, (i+1)): : j가 1부터 i까지 반복될 때
  • factorialDic[i] = factorialDic[i-1] * j : 1 팩토리얼은 0 x 1(자기자신) 이다. 여기서 0팩토리얼은 1로 위에서 정의 했으니까, 결국 1 x 1로 계산된다
factorialDic = {}
for i in range(11):
    if i == 0:
        factorialDic[i] = 1
    else:
        for j in range(1, (i+1)):
            factorialDic[i] = factorialDic[i-1] * j

print(f'factorialDic : {factorialDic}')

factorialDic : {0: 1, 1: 1, 2: 2, 3: 6, 4: 24, 5: 120, 6: 720, 7: 5040, 8: 40320, 9: 362880, 10: 3628800}

4. 수정

'딕셔너리 이름[키;key] = 값;value' 형태로 아이템을 수정한다

🏷️실습

date =0

#  ▼ 30번 반복 될 수 있게 설정( 문제가 30일 이니까, 30번 반복)
while True:
    date += 1

    myBodyInfo['몸무게'] = round((myBodyInfo['몸무게'] - 0.3), 2)
    print('몸무게: {}'.format(myBodyInfo['몸무게']))

    myBodyInfo['신장'] = round((myBodyInfo['신장'] + 0.001), 3)
    print('신장: {}'.format(myBodyInfo['신장']))

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

    if date >= 30:
        break

print(f'myBodyInfo: {myBodyInfo}')
print(f'myBMI: {round(myBMI, 3)}')

myBodyInfo : {'이름': 'gildong', '몸무게': 83.0, '신장': 1.8}
myBMI : 25.62
몸무게: 82.7
신장: 1.801

(중간 생략)

신장: 1.829
몸무게: 74.0
신장: 1.83
myBodyInfo: {'이름': 'gildong', '몸무게': 74.0, '신장': 1.83}
myBMI: 22.097

5. keys(), values() 반환/조회

(1) keys(), values() 반환

  • 키 값만 모아서 반환
  • 밸류 값만 모아서 반환

memInfo = {'이름':'홍길동', '메일':'hh@naver.com', '학년':'3', '취미':['농구', '게임']  }

ks = memInfo.keys()
print(f'ks : {ks}')
print(f'ks type : {type(ks)}')

vs = memInfo.values()
print(f'vs : {vs}')
print(f'vs type : {type(vs)}')

items = memInfo.items()
print(f'items : {items}')
print(f'items type : {type(items)}')

ks : dict_keys(['이름', '메일', '학년', '취미'])
ks type : <class 'dict_keys'>
vs : dict_values(['홍길동', 'hh@naver.com', '3', ['농구', '게임']])
vs type : <class 'dict_values'>
items : dict_items([('이름', '홍길동'), ('메일', 'hh@naver.com'), ('학년', '3'), ('취미', ['농구', '게임'])])
items type : <class 'dict_items'>

(2) (list()) 변환

data 형태를 list로 변환해서 사용도 가능

(3) for()을 이용한 조회

  • 단 2줄로 모든 key와 value 조회가 가능하다 ⭐
memInfo = {'이름':'홍길동', '메일':'hh@naver.com', '학년':'3', '취미':['농구', '게임']  }

for key in memInfo.keys():
    print(f'{key}: {memInfo[key]}')

이름: 홍길동
메일: hh@naver.com
학년: 3
취미: ['농구', '게임']

🏷️실습

  • (key 뽑기) for key in scores:
    : scores의 key 값만 조회
  • (value 뽑기) scores[key]
    : value가 구해지는 문장 (scores의 key = value 니까)
  • (value값 비교) if scores[key] < minScore:
    : value가 60 미만이면
  • (value 값을 바꿈, F학점으로) scores[key] = fStr
    : 그 key에 해당되는 value를 'fStr(fStr = 'F(재시험)')'로 수정/변경 할게
  • (Dic에 따로 저장)fDic[key] = fStr
    : 그리고 걔네만 따로 fDic에 모을게, fDic = {}는 F학점을 맞은 과목들만 모이게 됨
scores = {'kor':88, 'eng':55, 'mat':85, 'sci':57, 'his':82}
print(f'scores : {scores}')

minScore = 60
fStr = 'F(재시험)'
fDic = {}

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

print(f'scores: {scores}')
print(f'fDic: {fDic}')

scores : {'kor': 88, 'eng': 55, 'mat': 85, 'sci': 57, 'his': 82}
scores: {'kor': 88, 'eng': 'F(재시험)', 'mat': 85, 'sci': 'F(재시험)', 'his': 82}
fDic: {'eng': 'F(재시험)', 'sci': 'F(재시험)'}

6. 삭제하기

(1) del()

  • 삭제 방법 : del 딕셔너리이름 [key값]

(2) pop()

  • 삭제 방법 : 딕셔너리이름.pop(key값)
  • 데이터를 반환하면 삭제된 값(returnValue)을 볼 수 있음

🏷️실습

[최저]

  • minScoreKey = ' ' / maxScoreKey = ' ' : key 값을 설정
  • for key in scores.keys(): : 전체(scores.keys())에서 key 하나 씩 뽑기
  • score[key] : value 값 임
  • if score[key] < minScore: : 뽑은 value 값이 minScore 보다 작다면
  • minSCore = scores[key] : minSCore이 scores[key]로 할당 = 계속 반복이 되면 가장 작은 값을 얻어낼 수 있음
  • minScoreKey = key : key 값도 얻어 냄
scores = {'score1' : 8.9, 'score2':8.1, 'score3' : 8.5, 'score4' : 9.8, 'score5' : 8.8}
print('scores : {}'.format(scores))

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

for key in scores.keys():
    if scores[key] < minScore:
        minScore = scores[key]
        minScoreKey = key

    if scores[key] > maxScore:
        maxScore = scores[key]
        maxScoreKey = key

print('minScore : {}'.format(minScore))
print('minScoreKey : {}'.format(minScoreKey))

print('maxScore : {}'.format(maxScore))
print('maxScoreKey : {}'.format(maxScoreKey))

del scores[minScoreKey]
del scores[maxScoreKey]
print('scores : {}'.format(scores))

scores : {'score1': 8.9, 'score2': 8.1, 'score3': 8.5, 'score4': 9.8, 'score5': 8.8}
--------------------------------------------------
minScore : 8.1
minScoreKey : score2
maxScore : 9.8
maxScoreKey : score4
--------------------------------------------------
scores : {'score1': 8.9, 'score3': 8.5, 'score5': 8.8}

7. 유용한 기능s

(1) in, not in _ key 존재 유무 파악

key 존재 유무를 파악한다

(2) len()_ 아이템의 개수 파악

(3) clear()_ 모든 아이템을 삭제

  • 한개씩 삭제 : pop(), del()
  • 모두 삭제 : clear()

🏷️예제


출처/참고 : 제로베이스 데이터 스쿨
profile
비전공자의 데이터 공부법

0개의 댓글