.get instead of [key] for dictionary iterations - Deepstash

.get instead of [key] for dictionary iterations

Dictionaries are great data-types for storing values with an attribute field known as the key , in so-called key-value pairs . When extracting key-value pairs from dictionaries, avoid running into KeyError exceptions with the .get method instead of the more traditional [key] method. The .get method provides a default value if the key is not present.

In line 6-10 our program stops running because of the KeyError exception, but in line 11-14 our program continues, using the default 'undefined' string that is set in line 12 as the second argument of the .get method.

When you have the possibility of assigning a default value for accessing key-value pairs in a dictionary, always try to use the .get method to avoid your program from stopping prematurely, especially when in production.

2

17 reads

CURATED FROM

IDEAS CURATED BY

The idea is part of this collection:

Machine Learning With Google

Learn more about computerscience with this collection

Understanding machine learning models

Improving data analysis and decision-making

How Google uses logic in machine learning

Related collections

Read & Learn

20x Faster

without
deepstash

with
deepstash

with

deepstash

Personalized microlearning

100+ Learning Journeys

Access to 200,000+ ideas

Access to the mobile app

Unlimited idea saving

Unlimited history

Unlimited listening to ideas

Downloading & offline access

Supercharge your mind with one idea per day

Enter your email and spend 1 minute every day to learn something new.

Email

I agree to receive email updates