I'm importing a .txt list of words into a dictionary and print, "The word seen most was XXXX and it was seen X times." I can import the .txt list into a dictionary and sorted my dictionary by value so my most seen word is at the end of the list, but now I'm stuck. How do I print the last item in a dictionary without knowing what space it is at? Can I do something like print dict.values(max)?

Thanks!

Recommended Answers

All 6 Replies

print(max(dict.keys()))

Thanks tonyjv, I tried assigning the max(dict.items()) to a variable and printing that, which worked, but I couldn't strip away unnecessary characters.

a = max(freq.items())
print 'The most commonly seen word was', a[1],'seen', a[0],'times.'

#which prints
The most commonly seen word was ['Pear'] seen 5 times.

I also came up with another way to print the list to look cleaner (without around the word Pear) by using this code, but it prints all the dictionary items and not just the last one:

for key in sorted(dict):
    for name in dict[key]:
        print 'The most commonly seen word was', name,"seen", key,"times."

#which prints
The most commonly seen word was Apple seen 1 times.
The most commonly seen word was Banana seen 1 times.
The most commonly seen word was Orange seen 1 times.
The most commonly seen word was Pear seen 5 times.

I feel like I'm really close, I just need to either clean up how it prints in the first code I posted, or get it to print just the last line for the second code.

Thanks!

a[1][0]

?

or save

[item], key = max(freq.items()

What happens if you have more than one key with the same maximum? Instead of print, store the key and item if it is greater than the maximum so far.

a[1][0] ?

Well, when I do

a = max(freq.items())
#so now
a = ((5, ['Pear'])
a[0] = 5 
a[1] = ['Pear']
#which makes it easy to print my sentence using
print 'The most commonly seen word was', a[1],'seen', a[0],'times.'

I'm new to python so it doesn't matter if more than one key has the maximum at this point.

Seems I figured it out by combining my two codes.

a = max(freq.items())
    for key in a:
        print 'The most commonly seen bird was the', name,"seen", key,"times."
        return

Thanks for the help!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.