4th Street Bar Hive-Bar

Hive-Bar Powered by Hive beta-fdb5b5b

Community post

Python Tip for the Week

https://snipboard.io/UrMgWP.jpg

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.

3 upvotes $0.00

Replies (0)

Conversation

No replies yet

Replies will appear here as people join the conversation.

Review before signing

Posting as . Signing with . Keychain permission: Posting. Hive Keychain will ask you to approve this action next.


  
Technical details

Operation fingerprint: