Computer/Python

python OrderedDict

hexists 2014. 12. 4. 23:56

파이썬을 사용하다보면 Dict의 순서가 정렬되지 않아, 정렬이 필요한 경우가 있다.

이럴 때는 다음과 같이 하면 된다.


from collections import OrderedDict

all_ordered_dic = OrderedDict(sorted(all_dic.items(), key=lambda t: t[1]['status']))


1. collections에서 OrderedDict를 import 한 다음...


2. lambda를 이용해서 정렬한다.

여기서는 all_dic[key] = {'status': '+', ... } 와 같은 구조에서 value 중 'status' 값을 기준으로 정렬한다.

sorted(all_dic.items(), key=lambda t: t[1]['status']) 


3. OrderDict를 적용한다.


이렇게 하면... 내가 원하는 순서의 key, value를 사용할 수 있다.