Double dict.get: Get Values in a Nested Dictionary with Missing Keys

Double dict.get: Get Values in a Nested Dictionary with Missing Keys

You can use an if-else statement to get values in a nested dictionary with missing keys, but it is long and hard to read. 

A better way is to use the get method twice like below.

The first get method will return an empty dictionary if the key attr doesn’t exist. The second get method will return unknown if the key color doesn’t exist.

Link to my previous tips on Python dictionary.

Search

Related Posts

Related Posts

Scroll to Top

Work with Khuyen Tran

Work with Khuyen Tran