jbertz
jbertz

Reputation: 1

How do I print the first 'n' values of a dictionary?

Okay so I'm having a little bit of trouble with this function. I have a dictionary that contains the titles of a bunch of webpages, and their page count in the format of dict = { "Site" : "Count" }. My function currently sorts the dictionary by descending count order and prints out each entry. I want it to only do this for the first 100 entries but I haven't figured out a way without running into an infinite loop.

def sort_data(site_dict):    
sorted_dict = dict(sorted(site_dict.items(),
                          key = lambda item: item[1],
                          reverse = True))

for key, value in sorted_dict.items():
    print (count, ": ", key, " : ", value)
    count += 1
    print() 

Upvotes: 0

Views: 184

Answers (2)

martineau
martineau

Reputation: 123463

Here's how to do it using the enumerate() function I mentioned in a comment:

from operator import itemgetter
import random


def sort_data(site_dict, most_common=None):
    sorted_dict = dict(sorted(site_dict.items(), key=itemgetter(1), reverse=True))

    for i, (key, value) in enumerate(sorted_dict.items(), 1):
        if most_common and i > most_common:
            break
        print(f'{i:3} - {key:8}: {value:4}')


data = {f'site {n:3}': random.randrange(10000) for n in range(1000)}

sort_data(data, 100)

Upvotes: 0

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 95948

For this particular case, you should use a collections.Counter:

>>> import random
>>> data = {c:random.randint(0, 100) for c in 'abcdefghi'}
>>> data
{'a': 61, 'b': 58, 'c': 80, 'd': 39, 'e': 77, 'f': 14, 'g': 36, 'h': 97, 'i': 54}

Then use the .most_common method:

>>> collections.Counter(data).most_common(4)
[('h', 97), ('c', 80), ('e', 77), ('a', 61)]

But you could have accomplished something similar with just:

def sort_data(site_dict):    
    sorted_dict = dict(sorted(site_dict.items(),
                          key = lambda item: item[1],
                          reverse = True))
    count = 1
    for key, value in sorted_dict.items():
        print (count, ": ", key, " : ", value)
    print()
    if count == 100:
        break
    count += 1

A cleaner approach might be to use itertools.islice:

from itertools import islice

def sort_data(site_dict):    
    sorted_dict = dict(sorted(
        site_dict.items(),
        key = lambda item: item[1],
        reverse = True
    ))
    for key, value in islice(sorted_dict.items(), 100):
        print(f"{key} : {value}")

Upvotes: 2

Related Questions