본문 바로가기
Python

Python 딕셔너리 키 값, value 값으로 정렬하는 법

by Queen2 2022. 9. 21.
728x90
반응형

Hash문제를 풀다보면 dict를 정렬이 필요한 경우가 생기기 때문에 정렬하는 법을 정리해보려 합니다!

 

Key 값 기준으로 딕셔너리 정렬하는 법

 

1) OrderDict 사용

from collections import OrderedDict

dict = OrderedDict(sorted(dict.items()))

OrderedDict는 무작위 순서를 기억하는 일반 dict와 달리, 데이터가 삽입된 순서를 기억하는 똑똑한 dict입니다

(그래서 두 딕셔너리간 값과 정렬순서까지 동일한지를 확인할 때 유용하게 사용됩니다)

 

2) sorted 사용

dict(sorted(d.items()))

lambda로 x[0]을 굳이 명시해줄 필요 없습니다

 

 

Value 값 기준으로 딕셔너리 정렬하는 법

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

value기준 오름차순/내림차순 정렬은 reverse 값 true/false 지정을 통해서 할 수 있습니다

 

Source:

https://www.geeksforgeeks.org/python-sort-python-dictionaries-by-key-or-value/

 

Python | Sort Python Dictionaries by Key or Value - GeeksforGeeks

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

www.geeksforgeeks.org

https://stackoverflow.com/questions/9001509/how-do-i-sort-a-dictionary-by-key

728x90
반응형

댓글