Locked learning resources

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

Unlock This Lesson

Locked learning resources

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

Unlock This Lesson

Dictionaries

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

Python
 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.

Avatar image for DanielHao5

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.

Avatar image for Andras Novoszath

Andras Novoszath on March 13, 2019

Maybe like this?

new_dict = {}
Avatar image for Learn2Improve

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.