본문 바로가기
목차
Python

[Python] dictionary (Mapping type): basic

by ds31x 2023. 7. 11.
728x90
반응형

dictionary (dict)

Python에서 dictionary

  • key-value pair를 item으로 가지는
  • unordered
  • mutable
  • collection임: collections.abc.Mapping 의 구현!

set과 함께 curly bracket (or brace)를 사용하는데, empty dictionary가 바로 {}로 표현됨
(dictionary가 set보다 많이 이용되는 점이 반영된 듯...)


dictionary는 key와 value가 하나의 item에 가지고 있고, 해당 key를 통한 indexing이 가능함.

  • key는 set과 같이 unique 해야 한다.
  • key들은 set과 같이 unordered 임.

immutable object만이 key가 될 수 있음. 
mutable object는 hashable이지 않음.

2024.04.29 - [utils] - [CE] Hashing

 

[CE] Hashing

Hashing많은 메모리를 사용(indexing으로)하는 댓가로 검색에 필요한 계산 시간을 단축시키는 검색기법 또는 해당 검색기법이 가능하도록 자료구조를 만드는 방법적절한 hash function과 collision 해결방

ds31x.tistory.com


seqeunce 계열의 list와 달리,

dictionarykey를 통한 search 속도가 set과 마찬가지로 매우 빠르다.

Python 3.5에서는
items()메서드를 for문 등에서 사용할 때
각 실행 때마다 실제로 order가 바뀌었음 (=unordered).
하지만 3.7 부터는 고정된 순서로 반환됨.

주의할 건 해당 순서에 상관없이 같은 객체로 보므로
이를 구분하려면

collection.OrderedDict 를 사용하라.

 

일반적으로 item의 순서를 보장하는 dictionary로는 collections.OrderedDict 를 사용함.

2025.04.04 - [Python] - [Py] collection.OrderedDict

 

[Py] collection.OrderedDict

OrderedDict는 삽입된 순서를 보존하는 기능을 추가한 일종의 dict임.collections 모듈에서 제공.Python 3.7부터 built-in dict도 삽입 순서를 보존하게 되었음.하지만 OrderedDict는 그 외에 몇 가지 중요한 추가

ds31x.tistory.com


생성

curly bracket {}이나 생성자 dict()를 이용하며 주로 다음의 5가지 중 하나로 생성함.

d1 = {'a':1, 'b':2, 'c':3}
d2 = dict([('a':1), ('b':2), ('c':3)])
d3 = dict([['a':1], ['b':2], ['c':3]])
d4 = dict(a=1,b=2,c=3) # 이 경우엔 key가 무조건 str임.

k = ["a", "b", "c"]
v = [1, 2, 3]
d5 = dict(zip(k,v))

 

set과 함께 curly bracket을 사용하나, 비어있는 curly bracket의 경우엔 dict 를 의미함: dictionary가 보다 많이 사용되기 때문.

d = {}
print(f"{type(d) = }") # <class 'dict'>

add and remove

dictionary는 기본적으로 square bracket과 key를 통해 item에 접근할 수 있다.

  • dic[new_key]= value 와 같이, 새로운 키를 이용한 assignment를 통해 새로운 key-value pair가 추가됨.
  • dic[exist_key]= new_value 와 같이, 기존에 존재하는 키를 이용한 assignment는 해당 키에 해당하는 value를 새로운 값으로 교체함.
  • del dic[exist_key] 는 해당 키에 해당하는 key-value 쌍을 dictionary에서 제거한다.
    • 만약 지정한 키가 없는 경우KeyError가 발생한다.

in : membership operation

dictionary는 기본적으로 key를 통해 indexing되기 때문에, in membership operator을 통한 처리시 들에 대해 확인이 이루어짐.

list에 비해 고속으로 처리(hashing의 위력)되지만, sequence type들에 비해 보다 많은 메모리 사용량이 필요함. 

>>> dict = {'gachon': 100, 'bme': 200, 'elec': 300}
>>> 'bme' in dict
True
>>> 300 in dict
False

dictionary 의 메서드 정리

2023.07.11 - [Python] - [Python] Dictionary's methods

 

[Python] Dictionary's methods

Dictionary's methods비우기dic.clear()Dictionary instance (or object) dic을 전부 비움.모든 key-value 쌍들이 제거됨.값 얻어오기dic.get(key)key에 해당하는 키를 가지고 있는 value를 반환.만약 없다면 None이 반환됨.dic

ds31x.tistory.com


같이보면 좋은 자료들

https://dsaint31.tistory.com/515

 

[Python] (Data) Type: Summary

1. Type 이란?Programming에서 사용되는 모든 value 혹은 object 들의 종류 (category) 를 (data) type이라고 부름.수학에서 숫자의 종류(type)를 실수, 정수, 자연수 등으로 나누는 것을 생각하면 쉽다.Programming에

dsaint31.tistory.com

 

2024.04.15 - [Python] - [Python] collections.abc

 

[Python] collections.abc

2023.10.06 - [Pages] - [Python] Collectionscollections.abc 와 Python의 DataStructure.Python의 Data structure는 실제적으로 collections.abc 라는 abstract base class (abc) mechanism를 통한 hierarchy로 구성된다: type은 module임.일반적

ds31x.tistory.com

 

2023.10.06 - [Pages] - [Python] Collections

 

[Python] Collections

Python에는 여러 데이터를 담아두고 다룰 수 있는 다양한 컬렉션(collection) 클래스들이 있음.대표적으로 list, tuple, set, dict 등이 있는데 이들의 기능을 설명하는 abstract base class들로부터 시작하여 각

ds31x.tistory.com

 


728x90

'Python' 카테고리의 다른 글

[Python] list (sequence type) : summary  (0) 2023.07.12
[Python] set and frozenset  (0) 2023.07.12
[Python] Dictionary's methods  (0) 2023.07.11
[Python] 특정 점에서 직선에 수선의 발 구하기.  (0) 2023.07.11
[Python] atan2  (1) 2023.07.10