본문 바로가기
개발/Python3

python3 - [자료구조] Dictionary를 알아보자

by Devsong26 2021. 6. 15.

자바의 Map과 같은 자료구조라고 생각하면 된다.

key, value 쌍으로 이루어진 집합이다.

 

Dictionary

딕셔너리는 키로 인덱싱되는데, 모든 불변형을 사용할 수 있습니다; 문자열과 숫자들은 항상 키가 될 수 있습니다.

딕셔너리를 (한 딕셔너리 안에서) 키가 중복되지 않는다는 제약 조건을 가진 키: 값 쌍의 집합으로 생각하는 것이 최선입니다. 중괄호 쌍은 빈 딕셔너리를 만듭니다: {}. 중괄호 안에 쉼표로 분리된 키:값 쌍들의 목록을 넣으면, 딕셔너리에 초기 키:값 쌍들을 제공합니다; 이것이 딕셔너리가 출력되는 방식이기도 합니다.

딕셔너리의 주 연산은 값을 키와 함께 저장하고 주어진 키로 값을 추출하는 것입니다. del로 키:값 쌍을 삭제하는 것도 가능합니다. 이미 사용하고 있는 키로 저장하면, 그 키로 저장된 예전 값은 잊힙니다. 존재하지 않는 키로 값을 추출하는 것은 에러입니다.

출처: https://docs.python.org/ko/3/tutorial/datastructures.html#dictionaries

 

# key:value 쌍이 정의된 dictionary
d = {'1': 1, 'k': 'asdf'}

print(d['1']) # 1 
print(d['k']) # asdf

# 빈 dictionary
empty_d = {}

# key:value 쌍 추가
empty_d['a'] = 'a'
empty_d['b'] = 'b'

print(empty_d) # {'b': 'b', 'a': 'a'}

# 중복 key 정의 시, 마지막 입력값으로 value 대체
empty_d['a'] = 'replacement_a'

print(empty_d) # {'b': 'b', 'a': 'replacement_a'}

# key:value 쌍 삭제
del empty_d['b']

print(empty_d) # {'a': 'a'}

 

JSON과 Dictionary

Rest API의 Response는 포맷이 JSON이다.

python3에서는 JSON을 dictionary로 변경할 수 있다.

 

import json

response_json = '{"status":200,"message":"success","data":{"user_info":{"name":"syubrofo","job":"developer","lang":"python3"}}}'

json_dictionary = json.loads(response_json)
print(json_dictionary)

 

필자의 경우 변환된 json_dictionary의 특정 key에 매칭된 value에 대한 validation check가 필요했다.

 

Dictionary key check

value의 validation check를 하려면 key가 dictionary에 존재하는지 확인을 해야 한다.

dictionary에서 key의 존재 유무는 "in" keyword로 확인한다.

 

import json

response_json = '{"status":200,"message":"success","data":{"user_info":{"name":"syubrofo","job":"developer","lang":"python3"}}}'

json_dictionary = json.loads(response_json)
print(json_dictionary)

print("k" in json_dictionary) # False
print("status" in json_dictionary) # True

# json key에 json이 mapping된 경우 하위 json key check
if  "data" in json_dictionary and\
    "user_info" in json_dictionary['data'] and\
    "name" in json_dictionary['data']['user_info']:
        print(json_dictionary['data']['user_info']['name']) # syubrofo

 


더 많은 내용을 보시려면 아래를 참고하세요.


Reference

https://docs.python.org/ko/3/tutorial/datastructures.html#dictionaries

https://ko.wikipedia.org/wiki/JSON

https://stackoverflow.com/questions/1602934/check-if-a-given-key-already-exists-in-a-dictionary