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)
Latest posts by Tahmid Samin (see all)
- How to Take Multiple Input from User in Python. - 22 April, 2022
- The Use of Setdefault Dictionary Methodin Python - 21 April, 2022