Open In App

Python Dictionary Add Value to Existing Key

Last Updated : 23 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The task of adding a value to an existing key in a Python dictionary involves modifying the value associated with a key that is already present. Unlike adding new key-value pairs, this operation focuses on updating the value of an existing key, allowing us to increment, concatenate or otherwise adjust its value as needed.

For example, consider a dictionary d = {'a': 1, 'b': 2}. If we want to add 3 to the value of key 'a', we can directly modify the value like this: d['a'] += 3, resulting in d = {'a': 4, 'b': 2}.

Using direct Assignment

This is the efficient method for modifying the value associated with an existing key is direct in-place modification. When we know that the key exists, we can simply update its value.

Python
d = {'a': 1, 'b': 2}

# Add 3 to the value of key 'a'
d['a'] += 3
print(d)

Output
{'a': 4, 'b': 2}

Let's explore other methods to achieve the same :

Using get()

get() allows us to safely add a value to an existing key when we're not sure whether the key exists. This method returns the value of the key if it exists and a default value such as 0 if the key is missing .

Python
d = {'a': 1, 'b': 2}

# Add 3 to the value of key 'a', use 0 if 'a' doesn't exist
d['a'] = d.get('a', 0) + 3
print(d)

Output
{'a': 4, 'b': 2}

Using setdefault()

setdefault() can be used when we want to add a key with a default value if it does not already exist and it returns the value of the key, allowing us to modify it as needed

Python
d = {'a': 1, 'b': 2}

# Add 3 to the value of key 'a', use 0 if 'a' doesn't exist
d['a'] = d.setdefault('a', 0) + 3
print(d)

Output
{'a': 4, 'b': 2}

Using defaultdict

defaultdict from the collections module that automatically provides default values for missing keys. It's especially useful when the dictionary should have predefined default values, such as integers initialized to 0.

Python
from collections import defaultdict
d = defaultdict(int, {'a': 1, 'b': 2})

# Add 3 to the value of key 'a'
d['a'] += 3
print(d)

Output
defaultdict(<class 'int'>, {'a': 4, 'b': 2})

Next Article
Practice Tags :

Similar Reads