Selvam
Selvam

Reputation: 1093

Iterating through a dictionary for X number of times

Assume the dictionary contains more than 10 key-value pairs. The dictionary ought to be sorted by values (of integers). Print out the top 10 values (and corresponding keys). I think there is a better solution that what I have given here.

for keys in sorted(x):
   c=c+1
   if c>10:
      break
   else:
      print keys, x['keys']

Upvotes: 1

Views: 4423

Answers (4)

A.J.
A.J.

Reputation: 8985

You can iterate over dict for X number of times using the following code.

Python 3.8

def highest_contributor(self, top=1):
    slice_dict_only_to_keys = list(self.contributors.keys())[:top]
    for _key in slice_dict_only_to_keys:
        self.log("Top Contributor: {} ({})".format(_key, self.contributors[_key]))

Don't worry about integers and incrementing them with your code. You don't need them.

Simple, readable and Maintainable.

Upvotes: 0

John La Rooy
John La Rooy

Reputation: 304147

for key in sorted(x, key=x.get, reverse=True)[:10]:
    print key, x[key]

For really large dict you should consider using a heapq

from heapq import nlargest
for key in nlargest(10, x, key=x.get):
    print key, x[key]

Upvotes: 5

Tim Pietzcker
Tim Pietzcker

Reputation: 336148

topten = sorted(x.items(), key=lambda x:-x[1])[:10]

Upvotes: 0

Nitzan Shaked
Nitzan Shaked

Reputation: 13598

There is no order defined on dictionary keys, so the "first" keys are not well defined. Specifically, what you did is easier done with x.keys()[:10].

Upvotes: 1

Related Questions