dict.setdefault() method in Python

RMAG news

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)

| 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)

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)

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)

Related articles

Dictionary in Python

Python dict() Function

dict.get() method in Python

dict.update() method in Python

items(), keys() and values() methods in Python dictionary

dict.pop() in Python

dict.clear() method in Python

dict.fromkeys() method in Python

dict.popitem() method in Python

dict.copy() method in Python

Leave a Reply

Your email address will not be published. Required fields are marked *