Python
[Python] Dictionary Sort (정렬) lambda
bryan.oh
2019. 11. 5. 17:12
반응형
Dictionary Sort
Lambda
저번 글에서 썼던 dictionary 를 그대로~ ㅎ
score_dict = {
'sam':23,
'john':30,
'mathew':29,
'riti':27,
'aadi':31,
'sachin':28
}
저번 글엔 filter 거는걸 했었죠.
2019/11/05 - [Python] - [Python] Dictionary Filter
dict 의 스코어대로 정렬하는 방법입니다.
new_dict = sorted(score_dict.items(), key=lambda x:x[1], reverse=True)
print(new_dict)
# [('aadi', 31), ('john', 30), ('mathew', 29), ('sachin', 28), ('riti', 27), ('sam', 23)]
tuple 배열이 됩니다.
스코어빼고 이름만 정렬하고 싶다면,
new_dict = sorted(score_dict, key=lambda x: score_dict[x], reverse=True)
print(new_dict)
# ['aadi', 'john', 'mathew', 'sachin', 'riti', 'sam']
sorted 의 첫번째 파라메터를 score_dict.items() 에서 score_dict 로 바꾸면 되네요.
key 에서 x 는 dict 의 key가 됩니다. 점수로 정렬을 하려면 score_dict[key] 가 되어야 하기때문에 score_dict[x] 로 했습니다.
여기서 하나 더,
점수가 높은 3명만 뽑고 싶다면, 간단합니다.
new_dict = sorted(score_dict, key=lambda x: score_dict[x], reverse=True)[:3]
print(new_dict)
# ['john', 'riti', 'sam']
2019/11/05 - [Python] - [Python] Dictionary Filter
2019/10/22 - [Python] - [Python] MySQL connect , 간단 사용법
2019/02/14 - [Python] - [python]list dictionary sort multiple (여러 키로 정렬시키기)
2019/02/13 - [Python] - python dictionary 에서 max 값 가져오기 (key or value)
728x90
반응형