DEV Community

Main
Main

Posted on • Originally published at pynerds.com on

dict.setdefault() method in Python

The setdefault()method is used to retrieve a value from a dictionary given its key. If an item with the given key does not exist in the dictionary, it adds it and sets a given value for it.

The syntax is as shown below:


d.setdefault(key, value = None)
Enter fullscreen mode Exit fullscreen mode

| key | The key whose associated value is to be retrieved |
| value | The value to be set if the item with the given key does not exist. It defaults to None. |

If an item of the given key exists, its value is returned. Otherwise, the key with the specified value is added to the dictionary and the value is returned.


d = {
     'Tokyo': 'Japan',
     'Ottawa': 'Canada',
     'Kigali': 'Rwanda'
    }

value = d.setdefault('Kigali')
print(value)
Enter fullscreen mode Exit fullscreen mode

In the above example, we used the setdefault()method with a key that exist in the dictionary, 'Kigali'. The value associated with the key is returned which is 'Rwanda'.

Consider the following example:


d = {
     'Tokyo': 'Japan',
     'Ottawa': 'Canada',
     'Kigali': 'Rwanda'
    }

value = d.setdefault('Manilla')
print(value)

print(d)
Enter fullscreen mode Exit fullscreen mode

In the above example, the given key, 'Manilla' does not exist in the dictionary. Thesetdefault() method adds an item with the key and sets a default value of Noneto it because we did not specify another value.

with a default value given


d = {
     'Tokyo': 'Japan',
     'Ottawa': 'Canada',
     'Kigali': 'Rwanda'
    }

value = d.setdefault('Manilla', 'Philippines')
print(value)

print(d)
Enter fullscreen mode Exit fullscreen mode

Related articles


Image of Stellar post

Check out Episode 1: How a Hackathon Project Became a Web3 Startup 🚀

Ever wondered what it takes to build a web3 startup from scratch? In the Stellar Dev Diaries series, we follow the journey of a team of developers building on the Stellar Network as they go from hackathon win to getting funded and launching on mainnet.

Read more

Top comments (0)

Jetbrains image

Build Secure, Ship Fast

Discover best practices to secure CI/CD without slowing down your pipeline.

Read more

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay