Life2Coding
The Use of Setdefault Dictionary Method in Python

A Dictionary Problem:

Let’s create a function that takes an string as an argument and checks the number of occurrence of each letter in the given string. Finally it returns a dictionary in which each key = a letter and it’s value = number of that letter’s occurrence.

Input : “Saam”

Output : { “S”:1, “a”:2, “m”:1}

Solution 1:

def f(string):
   count={}
   for ch in string:
     if ch not in count:
        count[ch]=0
     count[ch]=count[ch]+1
   return(count)

Solution 2:

Before you solve this way, you should learn the use of “setdefault” dictionary method. Sometimes we have to set a value in a dictionary for a key only if that key doesn’t already has a value. This method helps to do this just in one line.It takes two argument. For example,if we call dic.setdefault(1st_arg,2nd_arg) ; the 1st argument is the key to check for,and the 2nd is the value to set at that key if the key doesn’t already exist.

def f(string):
   count={}
   for ch in string:
     count.setdefault(ch,0)
     count[ch]=count[ch]+1
   return(count)

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.