반응형
Python 사전(Dictionary)에서 값을 기준으로 topK를 추출하는 방법
python에서 dictionary를 갖고 있을때 (key, value)에서 value를 기반으로 topK를 뽑아내는 방법을 제시한다.
사전에서 값을 기준으로 정렬을 한 뒤에, [:N]을 이용해서 값을 추출할 수 있지만,
간단하게 한줄로 끝낼 수 있다. 기존 파이썬 패키지에 있는 heapq를 이용하면 된다.
heapq는 Heap queue algorithm으로 priority queue 알고리즘을 이용해서 값을 찾아낸다.
heaps은 binary tree를 이용하기 때문에 O(nlogn)
더 자세한 내용을 및 이론을 알고 싶으면
https://docs.python.org/2/library/heapq.html에서 8.4.3 Theory를 확인하면 좋다.
소스코드
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import heapq | |
topK = 10 | |
item_score_dict = {'1': 3,'2':2,'3':5,'4':1, '8':3} | |
ranklist = heapq.nlargest(topK, item_score_dict, key=item_score_dict.get) |
반응형
'Programming > Python' 카테고리의 다른 글
[Python] 튜블 정렬 하는 방법 (0) | 2018.10.20 |
---|---|
[Python] 쥬피터(jupyter) 노트북 백그라운드로 실행 (0) | 2018.10.20 |
파이썬(Python) 정규식(regex)으로 search, replace (0) | 2018.03.18 |
[파이썬] pickle을 사용해 dictionary 저장 및 로드 (0) | 2018.03.18 |
[파이썬] 튜블 정렬 하는 방법 (0) | 2018.03.18 |