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


Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay