파이썬

파이썬 - 딕셔너리

Gamcho 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']