키(key)와 값(value)를 이용해서 자료를 관리한다.
‘{ }’를 이용해서 선언하고, ’키:값’의 형태로 아이템을 정의한다.
키(key)를 이용해서 값(value)을 조회한다.
(존재하지 않는 키를 이용한 조회 시 에러가 발생한다)
ex) students = {'s1' : '홍길동', 's2' :'박찬호', 's3' :'이용규', 's4' : '박승철'}
print('students['s1']:{}'.format(students['key1']))
→ students[s1] : 홍길동
get(key)를 이용해서 값(value)을 조회 할 수 있다.
(get()은 key가 없어도 에러가 발생하지 않는다)
ex) print('students.get('s1'):{}'.format(students.get('s1'))) → students[s1] : 홍길동
전체키(key)와 값(value)를 조회할 수 있다.
ex)
for문을 이용한 조회
for key in ks:
print(f'key:{key}')
for idx, key in enumerate(ks):
print(f'idx, key: {idx}, {key}')
for value in vs:
print(f'value: {value}')
for idx, value in enumerate(vs):
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}')
for key in memInfo.key():
print(f'{key}: {memInfo[key]}')
Dictionary 추가
‘딕셔너리이름[키(key)] = 값(value)’ 형태로 아이템을 추가할 수 있다. (추가 하려는 키가 이미 있다면 기존 값이 변경된다.)
ex) students = {'s1' : '홍길동', 's2' :'박찬호', 's3' :'이용규', 's4' : '박승철'}
strdents['s4'] = '김지은'
strdents['s5'] = '박승호'
→students = {'s1' : '홍길동', 's2' :'박찬호', 's3' :'이용규', 's4' : '김지은', 's5' : '박승호'}
Dictionary 수정
수정할때에도 ‘딕셔너리이름[키(key)] = 값(value)’ 형태로 아이템을 수정한다.
Dictionary 삭제
-del과 key를 이용한 item 삭제
ex)students = {'s1' : '홍길동', 's2' :'박찬호', 's3' :'이용규', 's4' : '박승철'}
del students['s1']
→ students = {'s2' :'박찬호', 's3' :'이용규', 's4' : '박승철'}
-pop()와 key를 이용한 item 삭제
memInfo = {'이름':'홍길동', '메일':'gildong@gmail.com', '학년':'3', '취미':['게임','농구']}
returnValue = memInfo.pop('이름')
→print(f'memInfo:{memInfo}')
print(f'returnValue:{returnValue}')
memInfo : {'메일':'gildong@gmail.com', '학년':'3', '취미':['게임','농구']}
returnValue : 홍길동
Dictionary 기타
-in, not in 키워드를 이용하면 키(key)의 존재 유/무를 알 수 있다.
ex) print('이름' in memInfo) → True
-len()을 이용하면 딕셔너리 길이(아이템 개수)를 알 수 있다.
-clear()를 이용하면 모듬 아이템을 삭제한다.