Differences between dict.get(key) and dict[key] and which one to use?

When working with dictionaries, there are two ways to retrieve the value associated with a particular key: using the dict[key] syntax or using the dict.get(key) method. In this Python example, we will discuss the differences between these two approaches and analyse which one to use and when.

Some of the topics which will be helpful for understanding the program implementation better are:

1. Retrieving Values with dict[key]

The dict[key] syntax retrieves the value associated with a given key in a dictionary. For example:

my_dict = {'key1': 'value1', 'key2': 'value2'}
value = my_dict['key1']
print(value)
Output
'value1'

If the key does not exist in the dictionary, this will raise a KeyError. To avoid this, we can use the in keyword to check if the key exists in the dictionary first:

my_dict = {'key1': 'value1', 'key2': 'value2'}
if 'key3' in my_dict:
  value = my_dict['key3']
else:
  value = None
print(value)
Output
None

2. Retrieving Values with dict.get(key)

With dict(key) we do not need to care about whether the key exists in the dictionary or not. If the key does not exist in the dictionary, dict.get(key) returns None instead of raising a KeyError. For example:

my_dict = {'key1': 'value1', 'key2': 'value2'}
value = my_dict.get('key3')
print(value)
Output
None

In addition to that we can also specify a default value to return if the key does not exist in the dictionary:

my_dict = {'key1': 'value1', 'key2': 'value2'}
value = my_dict.get('key3', 'codingeek')
print(value)
Output
codingeek

3. Conclusion

In summary, both dict[key] and dict.get(key) are useful approaches for retrieving values from dictionaries in Python. In general, using dict[key] is preferred when you know that the key exists in the dictionary and you want to retrieve its value. However, if you’re not sure whether the key exists in the dictionary or you want to handle the case where it doesn’t exist, dict.get(key) is a safer choice.


Helpful Links

Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.

Also for examples in Python and practice please refer to Python Examples.

Complete code samples are present on Github project.

Recommended Books


An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding

Do not forget to share and Subscribe.

Happy coding!! ?

Recommended -

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
Index