Naive solution
You can write this in plain python:
>>> names = {'name1': 34, 'name2':45, 'name3': 98, 'name4':34, 'name5': 66}
>>> sorted_names = sorted(names.iteritems(), key=lambda (k, v): (-v, k))[:10]
>>> sorted_names
[('name3', 98), ('name5', 66), ('name2', 45), ('name1', 34), ('name4', 34)]
sorted
takes a key for sorting as the comparison
Then just print them as you wish:
>>> for name, score in sorted_names:
... print name, score
...
name3 98
name5 66
name2 45
name1 34
name4 34
Or just do it all at once:
>>> for name, score in sorted(names.iteritems(), key=lambda (k, v): (-v, k))[:10]:
... print name, score
...
name3 98
name5 66
name2 45
name1 34
name4 34
Using heapq
and in particular heapq.nsmallest
you can have a much more elegant solution:
>>> from heapq import nsmallest
>>> for name, score in nsmallest(10, names.iteritems(), key=lambda (k, v): (-v, k)):
... print name, score
...
name3 98
name5 66
name2 45
name1 34
name4 34
What I like about this solution is that nsmallest
could be implemented intelligently. It could be something like a lazy implementation like is described in this answer to Lazy Evaluation and Time Complexity. And so, you'd only do the minimum amount of work. Whereas the naive solution would have to sort the entire iterable before getting the first 10.