Python - Hash 데이터 구조를 가진 딕셔너리

HashMap

Java 에서는 key, value 구조를 갖는 데이터 객체를 해시 맵(HashMap) 으로 보통 사용합니다. 해시는 다음과 같은 이점을 가지고 있습니다.

  • 리스트 구조로 표현이 불가능하고, 네임(key)으로 구분 되는 자료를 구현하고자 할 때 사용
  • 빠른 데이터 접근 및 탐색이 필요할 때
  • 집계함수를 사용할 때

Python 에서의 Hash

파이썬에서는 Hash 구조를 갖는 데이터 객체를 Dictionary 로 표현합니다.

Dictionary

Init

딕셔너리 초기화 방식

## 다양한 초기화 방식

## 빈 딕셔너리 초기화
dict1 = {}
dict2 = dict()

## 값을 가지고 초기화
dict3 = {
  'name':'value'
  ,'age':20
}

## 이중 구조로 초기화 가능
dict4 = {
  'name': {
    'nickname':'ted'
    ,'realname':'rock'
  },
  'data':{
    'address':'',
    'etc':'',
  }
}

Get

딕셔너리 데이터를 가져오는 방법

기본적으로 dict[‘key’] 또는 dict.get(key, default) 로 사용하며 키 값에 해당하는 데이터가 없으면 default 가져온다.

dict = {'name':'ted','age':20}

## [] 
dict['name'] # ted
dict['address'] # None

## dict.get()
dict.get('name','null') # ted
dict.get('address','null') # null

Set

딕셔너리 데이터를 세팅하는 방법

Get 과는 다르게 [] 방식을 통해서만 값을 세팅합니다.

dict = {}
dict['name'] = 'ted'

dict['name'] # ted
dict.get('name','') # ted

Delete

딕셔너리 데이터를 삭제하는 방법

  • del dict[key]
  • dict.pop(key, default)
dict = {'name':'ted','age':20}
del dict['age'] # dict = {'name':'ted'}
del dict['address'] # key error !

dict.pop('name','none') # ted 가 리턴되며 삭제
dict.pop('address','none') # none 이 리턴되며 삭제된 데이터 없음 (del과는 다르게 에러가 나지 않고 default를 리턴함.)

Iterate

딕셔너리 데이터를 순회하는 방법

  • Key로만 순회하기
  • Key, value 동시 순회하기(items() 사용)
dict = {'name':'ted','age':20}
## key
for key in dict:
    print(key)

## key + value
for key, value in dict.items():
    print(key, value)

Etc.

  • in : 존재 여부 조회할 때 사용
    dict = {'name':'ted','age':20}
    print("name" in dict) # True
    print("address" in dict) # False
    
  • key 또는 value 만 뽑기 ```python dict = {‘name’:’ted’,’age’:20}

key only

print(dict.keys()) # [‘name’,’age’]

value only

print(dict.values()) # [‘ted’,20]

both

print(dict.items()) # [(‘name’,’ted’),(‘age’,20)] ```


© 2024. Chiptune93 All rights reserved.