티스토리 뷰
반응형
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
Getting key with maximum value in dictionary?
딕셔너리에서 값이 최대인 키를 가져오려면 어떻게 해야 하나요?
문제 내용
I have a dictionary where keys are strings, and values are integers.
저는 문자열을 키로 하고 정수를 값으로 가지는 딕셔너리가 있습니다.
stats = {'a': 1, 'b': 3000, 'c': 0}
How do I get the key with the maximum value? In this case, it is 'b'
.
최대값을 가지는 키를 가져오려면 어떻게 해야 하나요? 이 경우에는 'b'가 됩니다.
Is there a nicer approach than using an intermediate list with reversed key-value tuples?
키-값을 뒤집은 튜플을 사용하는 중간 리스트를 사용하는 것보다 더 나은 방법이 있나요?
inverse = [(value, key) for key, value in stats.items()]
print(max(inverse)[1])
높은 점수를 받은 Solution
max(stats, key=stats.get)
가장 최근 달린 Solution
Following are two easy ways to extract key with max value from given dict
다음은 주어진 딕셔너리에서 최대 값을 가진 키를 추출하는 두 가지 쉬운 방법입니다.
import time
stats = {
"a" : 1000,
"b" : 3000,
"c" : 90,
"d" : 74,
"e" : 72,
}
start_time = time.time_ns()
max_key = max(stats, key = stats.get)
print("Max Key [", max_key, "]Time taken (ns)", time.time_ns() - start_time)
start_time = time.time_ns()
max_key = max(stats, key=lambda key: stats[key])
print("Max Key with Lambda[", max_key, "]Time taken (ns)", time.time_ns() - start_time)
Output
결과
Max Key [ b ] Time taken (ns) 3100
Max Key with Lambda [ b ] Time taken (ns) 1782
Solution with Lambda expression seems to be performing better for smaller inputs.
람다 식을 사용한 해결책이 작은 입력에 대해 더 잘 수행됩니다.
출처 : https://stackoverflow.com/questions/268272/getting-key-with-maximum-value-in-dictionary
반응형
'개발 > 파이썬' 카테고리의 다른 글
Python 디렉토리에 있는 모든 목록 가져오기 (0) | 2022.12.09 |
---|---|
파이썬에서 파일 크기 가져오기 (0) | 2022.12.09 |
파이썬에서 리스트 길이 구하기 (0) | 2022.12.08 |
로컬 폴더의 모든 파일 삭제하기 (0) | 2022.12.08 |
리스트에서 아이템 무작위로 선택하기 (0) | 2022.12.08 |
댓글
공지사항
최근에 올라온 글