티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
How do I sort a list of dictionaries by a value of the dictionary?
값 기준으로 Dictionary 정렬하기
문제 내용
How do I sort a list of dictionaries by a specific key's value? Given:
특정 키 값을 기준으로 Dictionary 리스트를 정렬하려면 어떻게 해야 합니까? 아래와 같을 때:
[{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]
When sorted by name
, it should become:
이름별로 정렬하면 다음과 같아야 합니다.
[{'name': 'Bart', 'age': 10}, {'name': 'Homer', 'age': 39}]
높은 점수를 받은 Solution
The sorted()
function takes a key=
parameter
sorted() 함수는 key= 파라미터를 사용합니다.
newlist = sorted(list_to_be_sorted, key=lambda d: d['name'])
Alternatively, you can use operator.itemgetter
instead of defining the function yourself
또는 함수를 직접 정의하는 대신 operator.itemgetter를 사용할 수 있습니다.
from operator import itemgetter
newlist = sorted(list_to_be_sorted, key=itemgetter('name'))
For completeness, add reverse=True
to sort in descending order
완전성을 위해, 역방향을 추가하세요=True를 내림차순으로 정렬합니다.
newlist = sorted(list_to_be_sorted, key=itemgetter('name'), reverse=True)
가장 최근 달린 Solution
If performance is a concern, I would use operator.itemgetter
instead of lambda
as built-in functions perform faster than hand-crafted functions. The itemgetter
function seems to perform approximately 20% faster than lambda
based on my testing.
성능이 문제라면 람다 대신 operator.itemgetter를 사용할 것입니다. 내장 함수가 수작업 함수보다 더 빨리 수행되기 때문입니다. 제가 테스트한 결과 람다보다 아이템 게터 기능이 약 20% 더 빠른 것 같습니다.
From https://wiki.python.org/moin/PythonSpeed:
https://wiki.python.org/moin/PythonSpeed에서:
Likewise, the builtin functions run faster than hand-built equivalents. For example, map(operator.add, v1, v2) is faster than map(lambda x,y: x+y, v1, v2).
마찬가지로, 내장된 기능은 손으로 만든 기능보다 더 빨리 실행됩니다. 예를 들어 맵(operator.add, v1, v2)이 맵(lambda x, y: x+y, v1, v2)보다 빠릅니다.
Here is a comparison of sorting speed using lambda
vs itemgetter
.
다음은 람다와 itemgetter를 사용한 정렬 속도 비교입니다.
import random
import operator
# Create a list of 100 dicts with random 8-letter names and random ages from 0 to 100.
l = [{'name': ''.join(random.choices(string.ascii_lowercase, k=8)), 'age': random.randint(0, 100)} for i in range(100)]
# Test the performance with a lambda function sorting on name
%timeit sorted(l, key=lambda x: x['name'])
13 µs ± 388 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
# Test the performance with itemgetter sorting on name
%timeit sorted(l, key=operator.itemgetter('name'))
10.7 µs ± 38.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
# Check that each technique produces the same sort order
sorted(l, key=lambda x: x['name']) == sorted(l, key=operator.itemgetter('name'))
True
Both techniques sort the list in the same order (verified by execution of the final statement in the code block), but the first one is a little faster.
두 기술 모두 목록을 동일한 순서로 정렬하지만(코드 블록에서 최종 문을 실행함으로써 검증됨) 첫 번째 것이 조금 더 빠르다.
출처 : https://stackoverflow.com/questions/72899/how-do-i-sort-a-list-of-dictionaries-by-a-value-of-the-dictionary
'개발 > 파이썬' 카테고리의 다른 글
Dictionary에서 아이템(요소) 삭제 (0) | 2022.12.02 |
---|---|
가장 효율적인 변수 타입 확인 방법 (0) | 2022.12.02 |
리스트의 마지막 아이템을 가져오는 가장 효과적인 방법 (0) | 2022.12.02 |
리스트를 같은 크기의 청크로 분할하기 (0) | 2022.12.02 |
Python List의 append()와 extend()의 차이점 (0) | 2022.12.02 |