Python Use Get Method Over Square Brackets

It is better to use dict.get(‘key’) than dict[‘key’] when accessing values in a dictionary in Python. This is because dict.get(‘key’) returns None if the key does not exist, while dict[‘key’] raises a KeyError exception. 

Most Python developers are in a habit of using square brackets when accessing an element from a data structure like Dictionaries. There is no issue with square brackets but when it comes to a value that doesn’t exit it shows an ugly error. Now, to save yourself from that error you can use get method.

data_dict = {a:1, b:2,c:3}
print(data_dict['d'])
# KeyError: 'd'
print(data_dict.get('d'))
# None

If you have any questions about this code, you can drop a line in comment.

Comments

Popular posts from this blog

Python chr() Built in Function

Stock Market Predictions with LSTM in Python

Collections In Python

Python Count Occurrence Of Elements

Python One Liner Functions