sort dictionary on its key

nØthing spec¡al by Jimsjoo·2024년 7월 13일

Dictionary

목록 보기
2/2

정렬되어 있어야 맘이 편한 건 인지상정이다. 다음은 사전개체를 키(Key) 기준으로 정렬하는 예이다.

data = {'apple':5600,'orange':3500,'banana':5000} 
result = {k: data[k] for k in sorted(data)} 
assert result == {'apple': 5600, 'banana': 5000, 'orange': 3500}

위와 같은 기능을 아래와 같이 작성할 수 있다.

result = dict(sorted(zip(data.keys(),data.values())))
assert result == {'apple': 5600, 'banana': 5000, 'orange': 3500}
profile
harmonized or torn between programming and finance

0개의 댓글