본문 바로가기
programming language/Python

Python dictionary 안의 dictionary 데이터 타입

by __observer__ 2014. 11. 16.
반응형

Python 사용시 dictionary 안에 dictionary 를 계속 해서 추가하고 싶은 경우가 있습니다.

 

마치 우리가 사용하는 탐색기의 폴더 트리 구조와 같이 말이죠 .

 

Python에는 collections 이라는 모듈에서 deque 를 비롯하여 다양한 데이터 타입을 제공하는데 이중에 defaultdict 이라는 타입을 제공하고 있습니다.

 

이를 활용하면 위에 설명한 Tree 구조도 쉽게 만들 수 있습니다.

 

Tree() 구조에 대해서는 아래 주소에서 소개합니다.

 

https://gist.github.com/hrldcpr/2012250

 

위 주소에서 소개를 하므로 사용법에 대해서는 간단히 예를 들어보죠.

import collections
import json
def tree(): return collections.defaultdict(tree)
users = tree()
users['harold']['username'] = 'hrldcpr'
users['handler']['username'] = 'matthandlersux'
print(json.dumps(users))
for j,k in users.iteritems():
for l,m in k.iteritems():
print "%s %s %s" % (j,l, m)
view raw tree.py hosted with ❤ by GitHub

 

위 주소에서는 json.dumps 를 사용하여 사용하는 데이터 타입에 대해 console 에 나타냈는데, for 문을 통해서도 각 값들에 반복적으로 접근 할 수 있습니다.

 

위 코드를 실행해보면 아래와 같은 결과가 나옵니다.

 

{"harold": {"username": "hrldcpr"}, "handler": {"username": "matthandlersux"}}

harold username hrldcpr

handler username matthandlersux




반응형

댓글