Search code examples
pythondictionarycounttupleswords

Top Counts...return tuple format of output back to dictionary format


I need the top 10 words and their count, already contained in a dictionary, in the following format:

word count (e.g. hello 10)

I have the following code:

for word in word:
            if word not in counts:
                     counts[word] = 1
            else:
                    counts[word] += 1

for word in counts:
            top = sorted(counts.items())
            top_10 = top[:9]
print top

the output is a list with tuples inside: [('red', 5), ('blue', 2), ('green', 1), ...]

However, I need it in the format of :

red 5

blue 2

green 1

How can this be done???


Solution

  • replace

    print top
    

    with

    for k,v in top: print k, v