Word Frequency Counter

+1 RIDVAN KARABUDAK · December 26, 2014
Can someone explain this to me  i really don't understand   

for key, value in sorted(word_count.items(), key=operator.itemgetter(1)):

        print(key, value)

Post a Reply

Replies

Oldest  Newest  Rating
+1 Vaggelis Theodoridis · December 26, 2014
I'll explain up to a point but please someone continue or correct me.

sorted() is a built-in function that sorts any iterable
Can take an argument key, so we can specify the reference of the order if no key is provided it will sort from smaller to bigger or alphabeticall.

word_count is a dict. By specifing .items() we get a tuple of (key, value) for every "item".


Now the key=operator.itemgetter(1) 
First of all we imported operator, 
itemgetter() means that we specify which element we take into account so we can sort a list/tuple/set the way we want. 
1 means the second element.(we start counting from zero).
I beileve that it will sort by value cause in tuple (key, value), value is the second element so 1. Now im not 100% sure, please someone correct.

To wrap it up:
It will iterate through a sorted dict according to values and print the keys and values.
  • 1

Python

124,370 followers
About

This section is all about snakes! Just kidding.

Links
Moderators
Bucky Roberts Administrator