Python Tip for the Week
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:
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
- Python Tip for the Week
- Python - Console Improvements - Rich Library
- How Did I Learn Python? What About You?
- F strings in Python - How to use Them?
- Python - Some Things That Make it Unique
- Data Slicing in Python
- Various Ways to Get Data from Python Arrays
- Python Tips: MORE Parsing arguments for your application
- Python Tips: Parsing arguments for your application
- Python Tips: Parsing arguments for your application