How to get the top 10 students in the class using Python dict
Question: I have a dictionary with student-name and marks

    
    
    dict1 = {'name1': 34, 'name2':45, 'name3': 98, 'name4':34, 'name5': 66}
    

I want to get the top 10 student names along with their marks from the above
dict.

**Result:**

    
    
    name3 98
    name5 66
    name2 45
    name1 34
    name4 34
    

In case of multiple keys for same values, keys must be in alphabetical order
(Ex: name1 and name4 are in alphabetical order for same value 34)

How to get it done ?


Answer: Use
[`heapq.nlargest()`](http://docs.python.org/2/library/heapq.html#heapq.nlargest):

    
    
    from heapq import nlargest
    from operator import itemgetter
    
    for name, score in nlargest(10, dictionary.iteritems(), key=itemgetter(1)):
        print name, score
    

Demo:

    
    
    >>> for name, score in nlargest(10, dictionary.iteritems(), key=itemgetter(1)):
    ...     print name, score
    ... 
    name3 98
    name5 66
    name2 45
    name4 34
    name1 34
    

Note that because your sample dictionary is _smaller_ than the top `n` you
want, you could just as well have used `sorted()`:

    
    
    for name, score in sorted(dictionary.iteritems(), key=itemgetter(1), reverse=True):
        print name, score
    

but for any top `n` where `n` is smaller than `len(dictionary)` `heapq` is the
better choice.

Alternatively, use a `collections.Counter()` object, it has a `.most_common()`
method that gives you exactly that; the highest `n` scoring elements in the
counter:

    
    
    >>> scores = Counter(dictionary)
    >>> scores
    Counter({'name3': 98, 'name5': 66, 'name2': 45, 'name4': 34, 'name1': 34})
    >>> scores.most_common(3)
    [('name3', 98), ('name5', 66), ('name2', 45)]
    

