Add an item if the key does not exist in dict with setdefault in Python

Modified: | Tags: Python, Dictionary

In Python, you can add a new item to the dictionary (dict) with dict_object[key] = new_value. If the key already exists, the value is updated (overwritten) with the new value.

The setdefault() method allows you to add new keys with new values, without changing the values of existing keys.

This method is useful when you want to avoid modifying existing items.

Use the in keyword to check if a key exists in a dictionary. For more information, refer to the following article.

Add and update an item in the dictionary by specifying the key

To add or update items in a dictionary, use the following syntax:

dict_object[key] = new_value

If you specify a non-existent key, a new item is added. If you specify an existing key, the current value is updated (overwritten).

d = {'k1': 1, 'k2': 2}

d['k3'] = 3
print(d)
# {'k1': 1, 'k2': 2, 'k3': 3}

d['k1'] = 100
print(d)
# {'k1': 100, 'k2': 2, 'k3': 3}

For more information on adding multiple items at once or merging multiple dictionaries, see the following articles.

How to use the setdefault() method

In the setdefault() method, the first argument is the key and the second is the value.

If the key specified in the first argument does not exist, a new item is added.

d = {'k1': 1, 'k2': 2}

d.setdefault('k3', 3)
print(d)
# {'k1': 1, 'k2': 2, 'k3': 3}

The default value of the second argument is None. If the second argument is omitted, the item is added with a value of None.

d.setdefault('k4')
print(d)
# {'k1': 1, 'k2': 2, 'k3': 3, 'k4': None}

If the key specified as the first argument already exists, the existing item remains unchanged, regardless of the value specified as the second argument.

d.setdefault('k1', 100)
print(d)
# {'k1': 1, 'k2': 2, 'k3': 3, 'k4': None}

Return value of the setdefault() method

The setdefault() method returns the value for the specified key.

If the key does not exist, a new item is added with the value from the second argument, and that value is then returned.

d = {'k1': 1, 'k2': 2}

print(d.setdefault('k3', 3))
# 3

print(d)
# {'k1': 1, 'k2': 2, 'k3': 3}

If the second argument is omitted, the item whose value is None is added, and None is returned.

print(d.setdefault('k4'))
# None

print(d)
# {'k1': 1, 'k2': 2, 'k3': 3, 'k4': None}

If the key already exists, the value for that key is returned as-is.

print(d.setdefault('k1', 100))
# 1

print(d.setdefault('k1', -100))
# 1

print(d.setdefault('k1'))
# 1

print(d)
# {'k1': 1, 'k2': 2, 'k3': 3, 'k4': None}

Related Categories

Related Articles