딕셔너리(dictionary) : 전화번호부와 같이 키(key)와 값(value) 형태로 데이터를 저장하는 자료구조다.
파이썬에서 딕셔너리의 선언은 중괄호 {}를 사용하여 키와 값의 쌍으로 구성하면 된다.
형식 : 딕셔너리 변수 = {키1 : 값1, 키2 : 값2, 키:3 : 값3, ...}
student_info = {20140012:'Janhyeok', 20140059 : 'Jiyong', 20150234: 'JaeHong', 20140058 : 'Wonchul'}
print(student_info)
해당 변수에서 특정 값을 호출하는 방법
해당 값의 키를 대괄호 []안에 넣어 호출할 수 있다. 변수의 자료형을 정확히 모르고 호출한다면, 리스트로 오해한다.
student_info = {20140012:'Janhyeok', 20140059 : 'Jiyong', 20150234: 'JaeHong', 20140058 : 'Wonchul'}
print(student_info[20140012])
재할당과 데이터 추가
student_info = {20140012:'Janhyeok', 20140059 : 'Jiyong', 20150234: 'JaeHong', 20140058 : 'Wonchul'}
student_info[20140012] = "Lee"
print(student_info[20140012])student_info = {20140012:'Janhyeok', 20140059 : 'Jiyong', 20150234: 'JaeHong', 20140058 : 'Wonchul'}
student_info[20140012] = "Lee" # 재할당 Janhyok value 가 -> Lee로 변경
print(student_info[20140012])
# 데이터 추가
student_info[20192222] = "Seo"
print(student_info)
keys() = 키만 출력 리스트 형태로
values() = 값만 출력
student_info = {20140012:'Janhyeok', 20140059 : 'Jiyong', 20150234: 'JaeHong', 20140058 : 'Wonchul'}
print(student_info.keys()) # key값만 출력 - 리스트 형태
print(student_info.values()) # 딕셔너리의 value 값만 출력
키, 값 쌍을 모두 보여주고 싶다면 items() 함수를 사용한다.
student_info = {20140012:'Janhyeok', 20140059 : 'Jiyong', 20150234: 'JaeHong', 20140058 : 'Wonchul'}
student_info.items()