Agile Automation avatar

Python Tip for the Week

agileautomation

Published: 05 Feb 2024 › Updated: 05 Feb 2024Python Tip for the Week

Python Tip for the Week

image.png

Python has a lot of great functions and one that may not be known is the setDefaults() method of a dictionary.

This method is handy for ensuring that certain keys have values assigned without having to manually check for the existence of the key first. It can save from having to make that extra step or sometimes prevent getting errors in code. Another advantage is it makes the code more readable.

my_dict = {'apple': 1, 'banana': 2}
my_dict.setdefault('orange', 3) # Adds 'orange': 3 to the dictionary
print(my_dict) # Output: {'apple': 1, 'banana': 2, 'orange': 3}

my_dict.setdefault('apple', 4) # Does not change 'apple': 1 since 'apple' already exists
print(my_dict) # Output: {'apple': 1, 'banana': 2, 'orange': 3}

setdefault() adds the key-value pair if the key did not previously exist and if it already exists, it doesn't add anything.

Leave Python Tip for the Week to:

Written by

A software consultant specializing in control systems, automation and data collection. Python Development and tips.

Read more #python posts


Best Posts From Agile Automation

We have not curated any of agileautomation's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From Agile Automation