Clean Code
Python Counter: Count Word Frequency in One Line Instead of Six
· Count words in Python with Counter | 6 lines ka kaam, 1 line mein
Three ways to count words in Python: an if/else dict loop (6 lines), dict.get() (3 lines) and collections.Counter (1 line). Same output every time, and most_common(1) gives the top word. A small clean code habit for more readable Python.
The code
counts = {}
for w in words:
if w in counts:
counts[w] += 1
else:
counts[w] = 1counts = {}
for w in words:
counts[w] = counts.get(w, 0) + 1from collections import Counter
counts = Counter(words)counts.most_common(1)
![Animated sliding window over the array [2, 1, 5, 1, 3, 2]: a three-number window adds the new number and subtracts the old one, showing sums 8, 7, 9 and 6 and a maximum of 9.](https://i.ytimg.com/vi/NM5paB6_7wg/maxresdefault.jpg)
![Animated JavaScript comparisons: 0 == "0" is true, 0 == [] is true and "0" == [] is false, then a conversion lane turns [] into an empty string and then 0, ending on ===.](https://i.ytimg.com/vi/aXBolMH19gs/maxresdefault.jpg)
