Open In App

Add Same Key in Python Dictionary

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

The task of adding the same key in a Python dictionary involves updating the value of an existing key rather than inserting a new key-value pair. Since dictionaries in Python do not allow duplicate keys, adding the same key results in updating the value of that key. For example, consider a dictionary d = {'a': 1, 'b': 2}. If we want to update the value of the key 'a' to 3, the existing value 1 for 'a' will be replaced by 3, while the other key-value pairs in the dictionary remain unchanged. The output will be {'a': 3, 'b': 2}.

Using Square Bracket

This method is the most efficient way to add or update a key in a dictionary as it directly assigns a value to a specific key using subscript notation. If the key already exists, its value is updated and if the key does not exist then a new key-value pair is added to the dictionary.

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

d['a'] = 3
print(d)

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

Explanation: d['a'] = 3 directly updates the value of the key 'a' in the dictionary d.

Using update()

update() method to modify the value of an existing key or add a new key-value pair by passing another dictionary. It’s slightly less efficient for a single key due to internal overhead.

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

d.update({'a': 3})
print(d)

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

Explanation: update() is used to update the value of the key 'a' to 3 .

Using setdefault()

setdefault() method can be used to handle adding or updating the same key in a dictionary. It ensures a default value is set if the key doesn’t exist but if the key already exists, it retrieves the current value without changing it. This makes it useful for conditional updates or initializing missing keys.

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

d['a'] = d.setdefault('a', 0) + 2
print(d)

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

Explanation: setdefault() returns the value of the key if it exists and in this case, it's used to update 'a' by adding 2 to its current value.

Using dictionary comprehension

dictionary comprehension can be used to update the value of a specific key by applying conditional logic. It processes all keys in the dictionary and creates a new one, making it less efficient for modifying a single key. However, it allows flexibility when dealing with conditional updates.

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

d = {k: (3 if k == 'a' else v) for k, v in d.items()}
print(d)

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

Explanation: dictionary comprehension updates the value of key 'a' to 3 while leaving other keys like 'b' unchanged.


Next Article
Practice Tags :

Similar Reads