python

[Python] dict 정렬하기

seokhyun2 2020. 5. 27. 10:06

python에선 dict는 제일 많이 쓰는 데이터구조 중 하나죠.

dict는 dictionary의 줄임말이며, key-value 구조로 데이터를 저장해줍니다.

 

dict를 정렬하기 위해서는 sorted() 함수를 사용할 수 있습니다.

 

sorted(dict.items())

 

이렇게 사용하시면 dict가 정렬이 되며, 이 때 정렬은 key를 기준으로 정렬하게 됩니다.

 

item을 기준으로 정렬하고 싶다면, 아래와 같이 하시면 됩니다.

 

sorted(dict.items(), key=lambda x:x[1])

 

그리고, 만약 역순으로 정렬을 하고 싶다면, reverse=True 옵션을 넣어주시면 됩니다.

sorted(dict.items(), reverse=True)

sorted(dict.items(), key=lambda x:x[1], reverse=True)

 

dic = {'b':3, 'a':1, 'c':2}

sorted(dic.items())
# [('a', 1), ('b', 3), ('c', 2)]

sorted(dic.items(), key=lambda x:x[1])
# [('a', 1), ('c', 2), ('b', 3)]

sorted(dic.items(), reverse=True)
# [('c', 2), ('b', 3), ('a', 1)]

sorted(dic.items(), key=lambda x:x[1], reverse=True)
# [('b', 3), ('c', 2), ('a', 1)]