dict 정렬

발자·2022년 9월 13일
0

python

목록 보기
8/19

✏️ key 값으로 정렬

a = {'a' : 3, 'c' : 2, 'b' : 1}
sorted_a = sorted(a.items())
print(sorted_a)
# 출력
# [('a', 3), ('b', 1), ('c', 2)]

items()를 사용하여 Tuple pair로 이루어진 list가 출력된다.
이를 다시 dict로 바꿔줄 수 있다.

a = {'a' : 3, 'c' : 2, 'b' : 1}
sorted_a = dict(sorted(a.items()))
print(sorted_a)
# 출력
# {'a' : 3, 'b' : 1, 'c' : 2}

내림차순으로 정렬하려면 뒤에 reverse = True를 넣으면 된다.

a = {'a' : 3, 'c' : 2, 'b' : 1}
sorted_a = dict(sorted(a.items(), reverse = True))
print(sorted_a)
# 출력
# {'c': 2, 'b': 1, 'a': 3}

items()를 사용하지 않으면 dict도 Tuple pair도 아닌 정렬된 key 값으로만 이루어진 list가 반환된다.

a = {'a' : 3, 'c' : 2, 'b' : 1}
sorted_a = sorted(a)
print(sorted_a)
# 출력
# ['a', 'b', 'c']

여기서 value 값으로 정렬한 뒤 key 값을 리스트로 받을 수도 있다.

a = {'a' : 3, 'c' : 2, 'b' : 1}
sorted_a = sorted(a, key=lambda x : a[x])
print(sorted_a)
# 출력
# ['b', 'c', 'a']

✏️ value 값으로 정렬

a = {'a' : 3, 'c' : 2, 'b' : 1}
sorted_a = dict(sorted(a.items(), key = lambda x: x[1]))
print(sorted_a)
# 출력
# {'b': 1, 'c': 2, 'a': 3}

내림차순으로 정렬하려면 뒤에 reverse = True를 넣으면 된다.

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

0개의 댓글