Python Pro Tip: Start using Python defaultdict and Counter in place of dictionary

Python provides us with multiple ways to do the same thing.

But only one way I find beautiful.

"word_count_dict = {}for w in text.

split(" "): if w in word_count_dict: word_count_dict[w]+=1 else: word_count_dict[w]=1We could use defaultdict to reduce the number of lines in the code.

from Collections import defaultdictword_count_dict = defaultdict(int)for w in text.

split(" "): word_count_dict[w]+=1We could also have used Counter to do this, which according to me is the most preferable method for this problem.

from Collections import Counterword_count_dict = Counter()for w in text.

split(" "): word_count_dict[w]+=1If we use Counter, we can also get the most common words using a simple function.

word_count_dict.

most_common(10)—————————————————————[('I', 3), ('to', 2), ('the', 2)]Other use cases of Counter:# Count CharactersCounter('abccccccddddd')—————————————————————Counter({'a': 1, 'b': 1, 'c': 6, 'd': 5})# Count List elementsCounter([1,2,3,4,5,1,2])—————————————————————Counter({1: 2, 2: 2, 3: 1, 4: 1, 5: 1})So, why ever use defaultdict ?Notice that in Counter, the value is always an integer.

What if we wanted to parse through a list of tuples containing colors and fruits.

And wanted to create a dictionary of key and list of values.

The main functionality provided by a defaultdict is that it defaults a key to empty/zero if it is not found in the defaultdict.

s = [('color', 'blue'), ('color', 'orange'), ('color', 'yellow'), ('fruit', 'banana'), ('fruit', 'orange'),('fruit','banana')]d = defaultdict(list)for k, v in s: d[k].

append(v)print(d)—————————————————————defaultdict(<class 'list'>, {'color': ['blue', 'orange', 'yellow'], 'fruit': ['banana', 'orange', 'banana']})banana comes two times in fruit, we could use setd = defaultdict(set)for k, v in s: d[k].

add(v)print(d)—————————————————————defaultdict(<class 'set'>, {'color': {'yellow', 'blue', 'orange'}, 'fruit': {'banana', 'orange'}})ConclusionTo conclude, I will say that there is always a beautiful way to do anything in Python.

Search for it before you write code.

Going to StackOverflow is okay.

I go there a lot of times when I get stuck.

Always Remember:Creating a function for what already is provided is not pythonic.

Also if you want to learn more about Python 3, I would like to call out an excellent course on Learn Intermediate level Python from the University of Michigan.

Do check it out.

I am going to be writing more beginner friendly posts in the future too.

Let me know what you think about the series.

Follow me up at Medium or Subscribe to my blog to be informed about them.

As always, I welcome feedback and constructive criticism and can be reached on Twitter @mlwhiz.

.

. More details

Leave a Reply