-
파이썬 - 딕셔너리파이썬 2017. 11. 28. 00:02
딕셔너리 = {키 : 밸류}
키는 문자열과 숫자가 쓰일 수 있고, 값은 리스트 또한 쓰일 수 있다.
>>> student = { 'name': 'john', 'age' : 25, 'courses': ['math', 'compSci']}
#get() 키 값으로 밸류 값을 찾는다.
>>> student = { 'name': 'john', 'age' : 25, 'courses': ['math', 'compSci']}
>>> print(student.get('phone', 'Not found'))
Not found
#딕셔너리에 값 추가하기
>>> student = { 'name': 'john', 'age' : 25, 'courses': ['math', 'compSci']}
>>> student['phone'] = '555 - 5555'
>>> print(student)
{'name': 'john', 'age': 25, 'courses': ['math', 'compSci'], 'phone': '555 - 5555'}
#update{} 값을 최신으로 업데이트
>>> student = { 'name': 'john', 'age' : 25, 'courses': ['math', 'compSci']}
>>> student.update({'name': 'Jane', 'age': 21, 'phone': '222 - 2222'})
>>> print(student)
{'name': 'Jane', 'age': 21, 'courses': ['math', 'compSci'], 'phone': '222 - 2222'}
#삭제
>>> student = { 'name': 'john', 'age' : 25, 'courses': ['math', 'compSci']}
>>> del student['age']
>>> print(student)
{'name': 'john', 'courses': ['math', 'compSci']}
>>> student.pop('name')
'john'
>>> print(student)
{'courses': ['math', 'compSci']}
함수로 키, 밸류 값 출력찾기
>>> student.keys()
dict_keys(['name', 'age', 'courses'])
>>> student.values()
dict_values(['john', 25, ['math', 'compSci']])
>>> student.items()
dict_items([('name', 'john'), ('age', 25), ('courses', ['math', 'compSci'])])
for 반복문으로 키, 밸류 출력하기
>>> student = { 'name': 'john', 'age' : 25, 'courses': ['math', 'compSci']}
>>> for key, value in student.items():
print(key, value)
name john
age 25
courses ['math', 'compSci']
'파이썬' 카테고리의 다른 글
파이썬 - 함수(def)의 매개변수(parameter), 실행인자(argument) (0) 2017.11.29 파이썬 - 변수, 로컬/글로벌 개념 (0) 2017.11.29 파이썬 - 리스트, 튜플, 세트 (0) 2017.11.27 파이썬 - 포맷팅 예시 (0) 2017.11.26 파이썬 - 데이터 분류 함수 (0) 2017.11.26