스터디노트_자료구조_Dictionary_딕셔너리

MR.HAN·2023년 10월 28일

스터디노트

목록 보기
7/9

Dictionary : 키(key)와 값(value)을 이용해서 나열된 자료구조

  • key는 중복되면 안됨.
  • '{}'를 이용해서 선언하고, '키:값'의 형태로 아이템을 정의한다.
  • key와 value에는 숫자, 문자(열), 논리형, 컨테이너 자료형 가능하다.
  • 단, key에는 변경이 불가능한(immutable) 데이터만 올 수 있다.
students = {'s1':'홍길동', 's2':'박찬호', 's3':'이용규', 's4':['박세리', '박공주']}
print(students)
print(type(students))
>>
{'s1': '홍길동', 's2': '박찬호', 's3': '이용규', 's4': ['박세리', '박공주']}
<class 'dict'>

1. 조회

  • 딕셔너리는 key를 이용해서 value를 조회한다.
    존재하지 않는 key를 이용한 조회 시 에러 발생
students = {'s1':'홍길동', 's2':'박찬호', 's3':'이용규', 's4':'박승철', 's5':'김지은', 's6':['박세리', '박공주']}
print('students[\'s1\'] : {}'.format(students['s1']))
print('students[\'s6\'] : {}'.format(students['s6'][0]))
>>
students['s1'] : 홍길동
students['s6'] : 박세리
  • get(key)를 이용해서 value 조회 가능 (key가 없어도 에러 발생하지 않는다.)
students = {'s1':'홍길동', 's2':'박찬호', 's3':'이용규', 's4':'박승철', 's5':'김지은', 's6':['박세리', '박공주']}
print(students.get('s1'))
print(students.get('s7')) # --> 결과 None
>>
홍길동
None

2. 추가 / 변경

  • 'dictionary이름[key] = value' 형태로 아이템을 추가한다.
myInfo = {}

myInfo['이름'] = '박경진'
myInfo['전공'] = 'computer'
myInfo['메일'] = 'jin@gmail.com'
myInfo['학년'] = 3
myInfo['주소'] = 'korea seoul'
myInfo['취미'] = ['수영', '여행']

print(myInfo)

# 추가 하려는 키가 이미 있다면 기존 값이 변경된다.

myInfo['메일'] = 'han@gmail.com'

print(myInfo)
>>
{'이름': '박경진', '전공': 'computer', '메일': 'jin@gmail.com', '학년': 3, '주소': 'korea seoul', '취미': ['수영', '여행']}
{'이름': '박경진', '전공': 'computer', '메일': 'han@gmail.com', '학년': 3, '주소': 'korea seoul', '취미': ['수영', '여행']}

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

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}

ex. 하루에 몸무게(kg)와 신장(m)이 각각 -0.3kg, +0.001m씩 변한다고 할 때,
30일 후의 몸무게와 신장의 값을 저장하고 BMI 값도 출력하는 프로그램
(현재 신체정보는 아래의 딕셔너리에 저장되어 있다.)

myBodyInfo = {'이름':'gildong', '몸무게':83.0, '신장':1.8}

date = 0
while True:
    date += 1

    myBodyInfo['몸무게'] = round((myBodyInfo['몸무게'] - 0.3), 2)

    myBodyInfo['신장'] = round((myBodyInfo['신장'] + 0.001), 3)

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

    if date >= 30:
        break

print(f'myBodyInfo : {myBodyInfo}')
print(f'myBMI : {round(myBMI, 2)}')
>>
myBodyInfo : {'이름': 'gildong', '몸무게': 74.0, '신장': 1.83}
myBMI : 22.1

3. 내장 함수를 이용한 조회

  • keys()와 values() 함수로 전체 key와 value를 조회할 수 있다.
    list() 함수를 써서 완벽한 List로 변환하여 사용
memInfo = {'이름':'홍길동', '메일':'gildong@gmail.com', '학년':3, '취미':['농구', '게임']}

# key, value, item 조회 -> data type은 dict_

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

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

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

# 완전한 List로 변환

keys = list(keys)
print(f'keys : {keys}')
print(f'keys type: {type(keys)}')

values = list(values)
print(f'values : {values}')
print(f'values type: {type(values)}')

items = list(items)
print(f'items : {items}')
print(f'items type: {type(items)}')

# for문으로 list의 아이템 조회

for key in keys:
    print(f'key : {key}')

for idx, key in enumerate(keys):
    print(f'idx, key : {idx}, {key}')

for value in values:
    print(f'value : {value}')

for idx, value in enumerate(values):
    print(f'idx, value : {idx}, {value}')

for item in items:
    print(f'item : {item}')

for idx, item in enumerate(items):
    print(f'idx, item : {idx}, {item}')

# keys()와 for문을 이용한 전체 데이터 조회

for key in memInfo.keys():
    print(f'{key}:{memInfo[key]}')
>>
keys : dict_keys(['이름', '메일', '학년', '취미'])
keys type: <class 'dict_keys'>
values : dict_values(['홍길동', 'gildong@gmail.com', 3, ['농구', '게임']])
values type: <class 'dict_values'>
items : dict_items([('이름', '홍길동'), ('메일', 'gildong@gmail.com'), ('학년', 3), ('취미', ['농구', '게임'])])
items type: <class 'dict_items'>

keys : ['이름', '메일', '학년', '취미']
keys type: <class 'list'>
values : ['홍길동', 'gildong@gmail.com', 3, ['농구', '게임']]
values type: <class 'list'>
items : [('이름', '홍길동'), ('메일', 'gildong@gmail.com'), ('학년', 3), ('취미', ['농구', '게임'])]
items type: <class 'list'>

key : 이름
key : 메일
key : 학년
key : 취미
idx, key : 0, 이름
idx, key : 1, 메일
idx, key : 2, 학년
idx, key : 3, 취미
value : 홍길동
value : gildong@gmail.com
value : 3
value : ['농구', '게임']
idx, value : 0, 홍길동
idx, value : 1, gildong@gmail.com
idx, value : 2, 3
idx, value : 3, ['농구', '게임']
item : ('이름', '홍길동')
item : ('메일', 'gildong@gmail.com')
item : ('학년', 3)
item : ('취미', ['농구', '게임'])
idx, item : 0, ('이름', '홍길동')
idx, item : 1, ('메일', 'gildong@gmail.com')
idx, item : 2, ('학년', 3)
idx, item : 3, ('취미', ['농구', '게임'])

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

4. 삭제

  • del 키워드와 key를 이용한 item 삭제
memInfo = {'이름':'홍길동', '메일':'gildong@gmail.com', '학년':3, '취미':['농구', '게임']}
print(f'memInfo : {memInfo}')

del memInfo['메일']
print(f'memInfo : {memInfo}')

del memInfo['취미']
print(f'memInfo : {memInfo}')
>>
memInfo : {'이름': '홍길동', '메일': 'gildong@gmail.com', '학년': 3, '취미': ['농구', '게임']}
memInfo : {'이름': '홍길동', '학년': 3, '취미': ['농구', '게임']}
memInfo : {'이름': '홍길동', '학년': 3}
  • pop()과 key를 이용한 item 삭제
    함수이기 때문에 삭제된 값을 반환 가능 (del과의 차이점)
memInfo = {'이름':'홍길동', '메일':'gildong@gmail.com', '학년':3, '취미':['농구', '게임']}

returnValue = memInfo.pop('이름')
print(f'memInfo : {memInfo}')
print(f'returnValue : {returnValue}')
print(f'returnValue type : {type(returnValue)}')

returnValue = memInfo.pop('취미')
print(f'memInfo : {memInfo}')
print(f'returnValue : {returnValue}')
print(f'returnValue type : {type(returnValue)}')
>>
memInfo : {'메일': 'gildong@gmail.com', '학년': 3, '취미': ['농구', '게임']}
returnValue : 홍길동
returnValue type : <class 'str'>
memInfo : {'메일': 'gildong@gmail.com', '학년': 3}
returnValue : ['농구', '게임']
returnValue type : <class 'list'>

ex. 딕셔너리에 저장된 점수 중 최저 및 최고 점수를 삭제하는 프로그램

scores = {'s1':8.9, 's2':8.1, 's3':8.5, 's4':9.8, 's5':8.8}

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))
>>
minScore : 8.1
minScoreKey : s2
maxScore : 9.8
maxScoreKey : s4
scores : {'s1': 8.9, 's3': 8.5, 's5': 8.8}

5. 그 외 기능

  • in, not in 키워드로 key 존재 유/무 판단한다.
memInfo = {'이름':'홍길동', '메일':'gildong@gmail.com', '학년':3, '취미':['농구', '게임']}
print('이름' in memInfo)
print('메일' not in memInfo)
print('grade' in memInfo)
print('hobby' not in memInfo)
>>
True
False
False
True
  • len() 함수로 딕셔너리의 길이(아이템 개수)를 알 수 있다.
memInfo = {'이름':'홍길동', '메일':'gildong@gmail.com', '학년':3, '취미':['농구', '게임']}
print('len(memInfo) : {}'.format(len(memInfo)))
>>
len(memInfo) : 4
  • clear() 함수로 모든 아이템을 삭제한다.
memInfo = {'이름':'홍길동', '메일':'gildong@gmail.com', '학년':3, '취미':['농구', '게임']}
memInfo.clear()
print('memInfo : {}'.format(memInfo))
>>
memInfo : {}

ex. 개인 정보에 '연락처'와 '주민등록번호'가 있다면 삭제하는 코드

myInfo = {'이름':'Hong Gildong',
          '나이':'30',
          '연락처':'010-1234-5678',
          '주민등록번호':'840315-1234567',
          '주소':'대한민국 서울'}

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

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

print('myInfo : {}'.format(myInfo))
>>
myInfo : {'이름': 'Hong Gildong', '나이': '30', '주소': '대한민국 서울'}

0개의 댓글