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

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

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():

 1dictionary = {'Mahdi': 5, 'Lizbon': 6}
 2
 3# dict.get() takes a second value as a default
 4his_apples = dictionary.get('Mahdi', 0)
 5her_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.

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 = {}

Learn2Improve on Feb. 4, 2020

Hey DanielHao5,

There are 2 ways to define empty dict:

# 1. option
new_dict = {}

# 2. option
new_dict = dict()

Hope it helps.

Become a Member to join the conversation.