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


Top comments (0)