How to Use try-except While Assigning Value in Dict in Python

Try and except statements in Python are called exception handlers. These statements play a crucial role in case any unexpected errors occur. 

Try – The code you think will cause an error is placed inside the try block. It is just a trial and error method; if the code in the try block does not cause an error, the try block runs as regular lines of code.

Except –   It is a block in which the error is handled. 

Try and except clauses are utilized as the exception handler. The required statement is placed inside the try block if the program has any errors, the compiler checks for the except clauses.

If the error raised and the exception given in the except clause is similar, then the except block is executed. On the other hand, if there is no error in the try block, the compiler executes the try block and then skips except blocks.

Syntax for try-except

 # Critical Statements
except exception_name: 
 # Things to do if the error is rised

In Python, we can have multiple except classes for each try part.


It is a data type in Python. 

E.g.: {“name”: “Ram”, “Age”: “14”}

We can assign values to the keys here. The key is a name, and the value is Ram. This is because all the keys in dictionaries are unique, and we cannot have two or more keys in the same name.

Considering this example, we cannot have two or more keys as names. Therefore, dictionary keys must be unique.


Let us take an example coding problem. This problem is quite a famous one. 

print('Enter a space separated string:')
data = input()
str = data.split(" ")
dict = {}
for i in str:
     dict[i] += 1
   except KeyError:
     dict[i] = 1



Enter a space separated string:
Hello world welcome to python world

{'Hello': 1, 'world': 2, 'welcome': 1, 'to': 1, 'python': 1}

Have you guessed what this coding problem is? This is a program for word count.

In this program, what we do is that we get input string from the users and count the number of times the word has occurred in the string. For that, we have done that we iterate over the strings, and in each iteration, we take a word and check whether that word is in the dictionary.

If the word is not present in the dictionary, it raises an exception called the KeyError exception, so the exception block is called. Inside that exception block, we have just assigned the value for the word as one because if the word is not present in the dictionary, then it means that it is the first occurrence, so we assign one as the occurrence, and if the word is present in the dictionary the value of the word will be incremented by one.

That’s it for this tutorial.

Leave a Comment