개발

[Python] dict 출력시 한글 출력 문제

지승준 2015. 2. 24. 19:42

어떤 언어이건 간에 5년을 경험했다 하더라도,

새로운 형태의 해결 방식은 계속 나오더군요.

파이썬도 그랬습니다.


다음과 같은 dict 가 있습니다.


1
2
3
4
5
d={
    '_id':'12345',
    'kind':'abc',
    'name':'가나다'
}
cs


여기에서 '가나다'는 UTF-8 코드 입니다.

(나중에는 u'가나다' 라고 unicode로 설정하여도 마찬가지 입니다)


여기에서 'name'키의 값을 출력해 보겠습니다.


print d['name']

하면,

그 결과는

가나다


라고 결과가 잘 나옵니다.


그런데 문제는 dict 자체를 출력할 때 발생합니다.


1
2
print d
{'kind''abc''_id''12345''name''\xea\xb0\x80\xeb\x82\x98\xeb\x8b\xa4'}
cs


위와 같이 \xea.... 라고 나옵니다.

이 같은 원인은 dict 를 serialize 시키면서 문자를 출력시킬 때

인코딩 무시한 출력 때문입니다.


pprint.pprint(d)

print pprint.pformat(d)

명령 모두,

1
{'_id''12345''kind''abc''name''\xea\xb0\x80\xeb\x82\x98\xeb\x8b\xa4'}
cs

라는 결과가 나옵니다.


이제 해결방법을 보겠습니다.


1
2
3
4
5
6
7
8
9
import pprint
class MyPrettyPrinter(pprint.PrettyPrinter):
    def format(self, _object, context, maxlevels, level):
        if isinstance(_object, unicode):
            return "'%s'" % _object.encode('utf8'), True, False
        elif isinstance(_object, str):
            _object = unicode(_object,'utf8')
            return "'%s'" % _object.encode('utf8'), True, False
        return pprint.PrettyPrinter.format(self, _object, context, maxlevels, level)
cs


위와 같이 pprint의 출력 클래스를 상속받아

unicode 인 경우에는 UTF-8로 변환시킨 문자열을 리턴하고,

일반 UTF-8 인경우에는 애초 UTF-8로 되어 있던 문자도 다시 UTF-8로 인코딩시킨

유니코드를 다시 UTF-8로 반환한 결과를 리턴한 것입니다.


이렇게 하여 


MyPrettyPrinter().pprint(d)

print MyPrettyPrinter().pformat(d)

와 같이 출력을 시키면,


1
{'_id''12345',' kind''abc''name''가나다'}
cs


라는 원하는 결과가 나옵니다.



어느분께는 도움이 되셨기를...


http://egloos.zum.com/mcchae/v/11076302