Solution Review: Count with Dictionary
The solution to the 'Count with Dictionary' challenge.
We'll cover the following...
Press + to interact
from collections import defaultdictfrom collections import OrderedDictdef count_letters(message):d = defaultdict(int) # Making dictionary with intfor letter in message:d[letter] += 1 # Adding 1 with every repetition# Sorting on the basis of valuesreturn OrderedDict(sorted(d.items(), key = lambda t:t[1]))print(count_letters('Welcome to Educative'))
Explanation
In the code above, we first import defaultdict
and OrderedDict
to solve the problem. Now, look at the header of the count_letters
function at line 4. It takes message
as a parameter containing the string that we want to count the letters of. The only trick here was to know the value of default_factory
when ...