이제 데이터 공부 안하는 블로그

[파이썬 기초] 딕셔너리 (del, list, sorted, in, not in, dict, items) 본문

파이썬

[파이썬 기초] 딕셔너리 (del, list, sorted, in, not in, dict, items)

공사노비 2021. 9. 16. 10:12

 

 

딕셔너리는 데이터를 연관지어 배열의 형태로 저장하는 자료구조다.

ex) student = {"a": "김모모", "b" : "고영희", "c" : "박짱구"} 이렇게 생겼다. 대괄호안에 key값 : value 을 짝지어서  써 준다. 

  • 딕셔너리는 순서로 저장되지 않기 때문에 인덱싱이 불가능하다.
  • 대신 key 값으로 value 값 을 추출할 수 있다. 예를 들어 studnet["a] 를 입력하면 김모모 라는 value 값을 얻을 수 있다.
  • 같은 이름의 key값을 가질 수 없고 중복 key값이 들어오면 기존 값이 삭제 된다.

파이썬 100제 문제를 풀어보았다.

#문제 8 : 아래와 같은 딕셔너리를 만들었다. 출력값은?

>>> d = {'height':180,'weight':78,'weight':84,'temparture':36,'eyesight':1}
>>> print(d['weight'])

 

weight라는 key값이 2개가 있다. 이 경우 weight 키 값을 입력하면 출력값은 무엇이 나올까? 정답은 84.

딕셔너리는 같은 이름의 key 값을 가질 수 없고, 중복된 key 값이 들어오면 기존 값이 삭제되기 때문이다. 

 

del 함수 를 사용하면 키:값 쌍을 삭제할 수 있다.

>>>  d = {'height':180,'weight':78,'weight':84,'temparture':36,'eyesight':1}
>>>  del d['height']
>>> print(d)

{'weight': 84, 'temparture': 36, 'eyesight': 1}

 

list() 를 사용하면 딕셔너리에서 사용되고 있는 모든 키의 리스트를 삽인 순서대로 출력할 수 있다.

>>> d = {'height':180,'weight':78,'weight':84,'temparture':36,'eyesight':1}
>>> list(d)

['height', 'weight', 'temparture', 'eyesight']

 

sorted() 를 사용하면 정렬을 할 수 있다.

>>> d = {'height':180,'weight':78,'weight':84,'temparture':36,'eyesight':1}
sorted(d)

['eyesight', 'height', 'temparture', 'weight']

 

in 이나 not in 을 사용해서 하나의 키가 딕셔너리에 있는지 검사할 수 있다.

>>> d = {'height':180,'weight':78,'weight':84,'temparture':36,'eyesight':1}
>>> 'height' in d

True

 

>>> d = {'height':180,'weight':78,'weight':84,'temparture':36,'eyesight':1}
>>> 'height' not in d

False

 

dict() 을 사용하면 key-value 쌍들의 시퀸스로부터 직접 딕셔너리를 구성한다.

>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])

{'sape': 4139, 'guido': 4127, 'jack': 4098}

 

for문으로 루핑할 때 items() 메서드를 활용하면 key값고 그에 대응하는 value값을 동시에 얻을 수 있다.

>>>knights = {'a': '김모모', 'b': '고영희'}
>>> for k, v in knights.items():
             print(k, v)


a 김모모
b 고영희

 

 

참고자료 : https://docs.python.org/ko/3/tutorial/datastructures.html#dictionaries