Tuesday, 6 February 2024

Python's setdefault(): A Shortcut for Adding Keys with Defaults

The ‘setdefault()’ method is a dictionary method in Python that checks for a key's existence and assigning a default value if the key is not exists in the dictionary.

 

Its functionality can be summarized as follows:

 

a.   If the specified key already exists in the dictionary, the method returns the corresponding value associated with that key.

b.   If the key does not exist in the dictionary, setdefault() adds the key to the dictionary with the provided default value and then returns this default value.

 

set_default_value.py

def wordCount(str):
    dict = {}

    for word in str.split():
        count = dict.setdefault(word, 0)
        dict[word] = count+1

    return dict

str = '''Word Count Program
Welcome to the Word Count Program! This program will analyze the text you provide and count the number of words in it
'''

print(wordCount(str))

 

Output

{'Word': 2, 'Count': 2, 'Program': 1, 'Welcome': 1, 'to': 1, 'the': 3, 'Program!': 1, 'This': 1, 'program': 1, 'will': 1, 'analyze': 1, 'text': 1, 'you': 1, 'provide': 1, 'and': 1, 'count': 1, 'number': 1, 'of': 1, 'words': 1, 'in': 1, 'it': 1}

 

Above snippet defines a function called 'wordCount' that takes a string (str) as input and returns a dictionary containing the count of each word in the input string.

 

def wordCount(str)

This line defines a function named wordCount that takes a single parameter str, which is the input string.

 

dict = {}

This line initializes an empty dictionary named dict which will store the word counts.

 

for word in str.split()

This line iterates over each word in the input string. str.split() splits the input string into a list of words based on whitespace (spaces, tabs, etc.).

 

count = dict.setdefault(word, 0)

For each word encountered, this line either retrieves its current count from the dictionary dict, or if the word is not already in the dictionary, it sets the count to 0. The setdefault() method returns the value of the specified key if it exists, otherwise it sets the key to the specified value (0 in this case) and returns that value.

 

dict[word] = count+1

This line increments the count for the current word by 1. It updates the value associated with the key word in the dictionary dict.

 

return dict

After counting all the words in the input string, the function returns the dictionary containing the word counts.

 

In summary, this function takes a string as input, splits it into words, counts the occurrences of each word, and returns a dictionary where the keys are the unique words and the values are the counts of each word.

 

Previous                                                 Next                                                 Home

No comments:

Post a Comment