티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
How do I sort a dictionary by key?
딕셔너리 키값 기준으로 정렬하기
문제 내용
How do I sort a dictionary by its keys?
딕셔너리를 키로 정렬하려면 어떻게 해야 합니까?
Example input:
입력 예제:
{2:3, 1:89, 4:5, 3:0}
Desired output:
원하는 출력:
{1:89, 2:3, 3:0, 4:5}
높은 점수를 받은 Solution
Note: for Python 3.7+, see this answer
참고: Python 3.7+의 경우 다음 답변을 참조하십시오.
Standard Python dictionaries are unordered (until Python 3.7). Even if you sorted the (key,value) pairs, you wouldn't be able to store them in a dict
in a way that would preserve the ordering.
표준 파이썬 딕셔너리는 (파이썬 3.7까지) 순서가 없다. (키, 값) 쌍을 정렬하더라도 순서를 유지하는 방식으로 dict에 저장할 수 없습니다.
The easiest way is to use OrderedDict
, which remembers the order in which the elements have been inserted:
가장 쉬운 방법은 요소가 삽입된 순서를 기억하는 OrderedDict를 사용하는 것입니다.
In [1]: import collections
In [2]: d = {2:3, 1:89, 4:5, 3:0}
In [3]: od = collections.OrderedDict(sorted(d.items()))
In [4]: od
Out[4]: OrderedDict([(1, 89), (2, 3), (3, 0), (4, 5)])
Never mind the way od
is printed out; it'll work as expected:
출력 방식은 신경 쓰지 마십시오. 예상대로 작동할 것입니다.
In [11]: od[1]
Out[11]: 89
In [12]: od[3]
Out[12]: 0
In [13]: for k, v in od.iteritems(): print k, v
....:
1 89
2 3
3 0
4 5
Python 3
파이썬 3
For Python 3 users, one needs to use the .items()
instead of .iteritems()
:
파이썬 3 사용자의 경우 .items() 대신 .iteritems()를 사용해야 합니다.
In [13]: for k, v in od.items(): print(k, v)
....:
1 89
2 3
3 0
4 5
가장 최근 달린 Solution
Here is the performance of the suggested solutions:
제안된 솔루션의 성능은 다음과 같습니다.
from collections import OrderedDict
from sortedcontainers import SortedDict
import json
keys = np.random.rand(100000)
vals = np.random.rand(100000)
d = dict(zip(keys, vals))
timeit SortedDict(d)
#45.8 ms ± 780 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
timeit sorted(d.items())
#91.9 ms ± 707 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
timeit OrderedDict(sorted(d.items(), key=lambda x: x[0]))
#93.7 ms ± 1.52 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
timeit dict(sorted(dic.items()))
#113 ms ± 824 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
timeit OrderedDict(sorted(dic.items()))
#122 ms ± 2.65 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
timeit json.dumps(d, sort_keys=True)
#259 ms ± 9.42 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
As we see, Grant Jenks's solution is by far the fastest.
보시다시피 그랜트 젱크스의 솔루션이 단연코 가장 빠릅니다.
출처 : https://stackoverflow.com/questions/9001509/how-do-i-sort-a-dictionary-by-key
'개발 > 파이썬' 카테고리의 다른 글
파이썬에서 파일 크기 확인하기 (0) | 2022.12.05 |
---|---|
Python에서 argparse로 양의 정수만 허용하기 (0) | 2022.12.05 |
type object 'datetime.datetime' has no attribute 'datetime' 오류 수정하기 (0) | 2022.12.05 |
ImportError: numpy.core.multiarray failed to import 수정하기 (0) | 2022.12.05 |
Pandas 데이터 프레임에서 여러 열 선택 (0) | 2022.12.05 |