How can I Python dictionary add a new key to an existing dictionary?

How can I Python dictionary add a new key to an existing dictionary? I know dictionaries don’t have an .add() method, so what is the proper way to add a new key-value pair?

Hello Everyone,

Using Assignment: You can add a new key-value pair to a dictionary by directly assigning the value to the key.

my_dict = {'a': 1, 'b': 2}  
my_dict['c'] = 3  # Adds new key 'c' with value 3  
print(my_dict)  # Output: {'a': 1, 'b': 2, 'c': 3}  

This method is simple and efficient. If the key already exists, it will update the value associated with that key. Honestly, it’s probably the go-to for quick and small updates.

Good one, @devan-skeem! But if you’re looking for something a bit more versatile, you can try the update() method. It’s a great way to add multiple key-value pairs or integrate another dictionary into yours.

my_dict = {'a': 1, 'b': 2}  
my_dict.update({'c': 3})  # Adds new key 'c' with value 3  
print(my_dict)  # Output: {'a': 1, 'b': 2, 'c': 3}  

And here’s where it shines:

my_dict.update({'d': 4, 'e': 5})  # Adds multiple keys  
print(my_dict)  # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}  

For larger updates or merging dictionaries, this makes life much easier when working with a Python dictionary add operation.

Great points, @alveera.khn Let me throw another option into the mix—setdefault(). It’s perfect if you want to add a key only if it doesn’t already exist.

my_dict = {'a': 1, 'b': 2}  
my_dict.setdefault('c', 3)  # Adds 'c' if it's not already in the dictionary  
print(my_dict)  # Output: {'a': 1, 'b': 2, 'c': 3}  

Here’s the catch: If the key already exists, it leaves it alone and just returns the current value.

my_dict.setdefault('a', 10)  # Won’t overwrite 'a'  
print(my_dict)  # Output: {'a': 1, 'b': 2, 'c': 3}  

So, if you’re tackling a scenario where you want to ensure no overwrites while performing a Python dictionary add, this method is worth exploring.