How to implement sort dictionary in Python?


  • -1
    W
    class Solution(object):
        def topKFrequent(self, nums, k):
            dict1={}
            for i in range(len(nums)):
                if nums[i] not in dict1:
                    dict1[nums[i]]=1
                else:
                    dict1[nums[i]]+=1
            def keyfunction(n):
                return dict1[n]
            re=[]
            for key in sorted(dict1, key=keyfunction, reverse=True)[:k]:
                re.append(key)
            return re

  • 0
    M
    from collections import Counter
    import heapq
    
    class Solution(object):
        def topKFrequent(self, nums, k):
            """
            :type nums: List[int]
            :type k: int
            :rtype: List[int]
            """
            counts = Counter(nums)
            top_k = []
            
            for val, count in counts.iteritems():
                if len(top_k) < k or count > top_k[0][0]:
                    heapq.heappush(top_k, (count, val))
                if len(top_k) > k:
                    heapq.heappop(top_k)
    
            return [heapq.heappop(top_k)[1] for _ in xrange(k)][::-1]

  • 0
    C

    You can use sorted() to get a list of keys sorted by values.

    class Solution(object):
        def topKFrequent(self, nums, k):
    
            frequent_dict = {}
    
            for _ in range(len(nums)):
                if nums[_] in frequent_dict:
                    frequent_dict[nums[_]] += 1
                else:
                    frequent_dict[nums[_]] = 1
        
            freq_nums = sorted(frequent_dict, key = frequent_dict.get, reverse = True)
    
            return freq_nums[:k]

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.