Python Tip for the Week

in Python9 months ago (edited)

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.