Programming

python dictionary 정렬하기

engyjoon 2021. 1. 19. 10:31

sorted 함수를 사용해 python dictionary를 정렬할 수 있다.


[방법1] lambda 표현식 사용

dict_a = {'a': 1, 'b': 2, 'c': 3}
print(sorted(dict_a.items(), key=lambda x: x[1], reverse=True))

[('c', 3), ('b', 2), ('a', 1)]


[방법2] itemgetter 함수 사용

from operator import itemgetter

dict_a = {'a': 1, 'b': 2, 'c': 3}
print(sorted(dict_a.items(), key=itemgetter(1), reverse=True))

[('c', 3), ('b', 2), ('a', 1)]