Dictionary를 value로 정렬하려면 어떻게 해야 합니까?
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
How do I sort a dictionary by value?
Dictionary를 value로 정렬하려면 어떻게 해야 합니까?
문제 내용
I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.
데이터베이스의 두 필드(문자열 필드와 숫자 필드)에서 읽은 값의 Dictionary가 있습니다. 문자열 필드는 고유하므로 사전의 키입니다.
I can sort on the keys, but how can I sort based on the values?
키는 정렬할 수 있는데 값을 기준으로 정렬하려면 어떻게 해야 하나요?
Note: I have read Stack Overflow question here How do I sort a list of dictionaries by a value of the dictionary? and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution to sort either in ascending or descending order.
참고: 사전의 값을 기준으로 사전 목록을 정렬하려면 어떻게 해야 합니까? 코드를 변경하여 사전 목록을 가질 수 있지만, 실제로는 사전 목록이 필요하지 않기 때문에 오름차순 또는 내림차순으로 정렬할 수 있는 더 간단한 솔루션이 있는지 알고 싶었습니다.
높은 점수를 받은 Solution
Python 3.7+ or CPython 3.6
Python 3.7+ 또는 CPython 3.6
Dicts preserve insertion order in Python 3.7+. Same in CPython 3.6, but it's an implementation detail.
Python 3.7+에서 삽입 순서를 유지합니다. CPython 3.6에서도 동일하지만 구현 세부 정보입니다.
>>> x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
>>> {k: v for k, v in sorted(x.items(), key=lambda item: item[1])}
{0: 0, 2: 1, 1: 2, 4: 3, 3: 4}
or
또는
>>> dict(sorted(x.items(), key=lambda item: item[1]))
{0: 0, 2: 1, 1: 2, 4: 3, 3: 4}
Older Python
오래된 파이썬
It is not possible to sort a dictionary, only to get a representation of a dictionary that is sorted. Dictionaries are inherently orderless, but other types, such as lists and tuples, are not. So you need an ordered data type to represent sorted values, which will be a list—probably a list of tuples.
사전을 정렬할 수 없으며 정렬된 사전의 표현만 가져옵니다. 사전은 본질적으로 순서가 없지만 목록과 튜플과 같은 다른 유형은 그렇지 않다. 따라서 정렬된 값을 나타내려면 정렬된 데이터 유형이 필요하며, 목록(아마도 튜플 목록)이 될 것입니다.
For instance,
예를 들어.
import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(1))
sorted_x
will be a list of tuples sorted by the second element in each tuple. dict(sorted_x) == x
.
sorted_x는 각 튜플에서 두 번째 요소에 의해 정렬된 튜플의 목록입니다. dict(details_x) == x.
And for those wishing to sort on keys instead of values:
값 대신 키를 정렬하려는 사용자를 위해:
import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(0))
In Python3 since unpacking is not allowed we can use
파이썬3에서는 언팩이 허용되지 않기 때문에 우리는 사용할 수 있다.
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=lambda kv: kv[1])
If you want the output as a dict, you can use collections.OrderedDict
:
출력을 딕트로 사용하려면 collections.OrderedDict 를 사용할 수 있다:
import collections
sorted_dict = collections.OrderedDict(sorted_x)
가장 최근 달린 Solution
Starting from Python 3.6, dict
objects are now ordered by insertion order. It's officially in the specifications of Python 3.7.
파이썬 3.6부터 dict 객체는 삽입 순서에 따라 정렬된다. 그것은 공식적으로 파이썬 3.7의 사양에 있다.
>>> words = {"python": 2, "blah": 4, "alice": 3}
>>> dict(sorted(words.items(), key=lambda x: x[1]))
{'python': 2, 'alice': 3, 'blah': 4}
Before that, you had to use OrderedDict
.
그 전에는 Ordered Dict를 사용해야 했습니다.
Python 3.7 documentation says:
파이썬 3.7 문서는 다음과 같다:
Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was implementation detail of CPython from 3.6.
버전 3.7에서 변경됨: 사전 순서는 삽입이 보장됨 이 동작은 3.6부터 CPython의 구현 세부 사항이었습니다.
출처 : https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value