Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Dictionaries

Give Feedback

In this lesson, you learned the pythonic way to retrieve data from dictionaries. Dictionary objects have a get() method that allows you to retrieve data without raising errors when the requested data does not exist. get() takes an optional default value as an argument.

The code sample below shows the correct way to retrieve data from a dictionary using get():

 1 dictionary = {'Mahdi': 5, 'Lizbon': 6}
 2 
 3 # dict.get() takes a second value as a default
 4 his_apples = dictionary.get('Mahdi', 0)
 5 her_apples = dictionary.get('Jennifer', 0)

Instead of raising a KeyError, line 5 will simply return 0. This approach is much better than trying to access dictionary keys and then catching any errors that may arise.

Comments & Discussion

DanielHao5 on March 13, 2019

Good Tips. Another question is - how to set the dictionary first? Meaning to initiaize the dictionary - more Pathonic way? Thanks.

Andras Novoszath on March 13, 2019

Maybe like this?

new_dict = {}

Become a Member to join the conversation.