반응형
Python 사용시 dictionary 안에 dictionary 를 계속 해서 추가하고 싶은 경우가 있습니다.
마치 우리가 사용하는 탐색기의 폴더 트리 구조와 같이 말이죠 .
Python에는 collections 이라는 모듈에서 deque 를 비롯하여 다양한 데이터 타입을 제공하는데 이중에 defaultdict 이라는 타입을 제공하고 있습니다.
이를 활용하면 위에 설명한 Tree 구조도 쉽게 만들 수 있습니다.
Tree() 구조에 대해서는 아래 주소에서 소개합니다.
https://gist.github.com/hrldcpr/2012250
위 주소에서 소개를 하므로 사용법에 대해서는 간단히 예를 들어보죠.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
위 주소에서는 json.dumps 를 사용하여 사용하는 데이터 타입에 대해 console 에 나타냈는데, for 문을 통해서도 각 값들에 반복적으로 접근 할 수 있습니다.
위 코드를 실행해보면 아래와 같은 결과가 나옵니다.
{"harold": {"username": "hrldcpr"}, "handler": {"username": "matthandlersux"}}
harold username hrldcpr
handler username matthandlersux
반응형
'programming language > Python' 카테고리의 다른 글
Python Computer Algebra System(CAS) package sympy (0) | 2014.12.03 |
---|---|
Python Pyzo, IEP (0) | 2014.12.03 |
Python 배열의 인덱스도 보기 enumerate (0) | 2014.11.30 |
Python Recursive File Search, Delete (0) | 2014.11.30 |
Eclipse Python Plugin Pydev 설치 (0) | 2014.11.15 |
Python에서 Clipboard 사용하기 pyperclip (0) | 2014.04.22 |
Python BeautifulSoup 를 사용한 로또 번호 불러오기 (2) | 2014.04.21 |
ipython으로 unique 하게 sorting 하기 (0) | 2013.11.26 |
댓글