/  Technology   /  How can I add new keys to a dictionary?

How can I add new keys to a dictionary?

How can I add new keys to a dictionary?


Dictionary is an unordered collection of data in the form of key-value pairs separated by commas inside curly brackets. Dictionaries are indexed by keys. They are generally optimized to retrieve values when the key is known. Values (definitions) are mapped to a specific key (words) similar to that of a dictionary in the real world. 

Now our task is to add new keys to a dictionary after its initialisation.


1. Using subscript notation:

The first method is using the subscript notation. It looks the below mentioned way

dict_name[new_dict_key]= new_dict_value 

This method creates a new key\value pair to the existing dictionary by assigning the value to the key. If the key doesn’t exist, it adds it and points it to the value. If the key already exists, the previous reference of the value will be overwritten.

We have taken a dictionary named dict with the following key-value pairs.

And added two new keys with their corresponding values using the subscript notation.


2. Using update():

It would be a tedious task if we want to add a lot of key-value pairs using the subscript notation. Using the update() function, we can add multiple keys to a dictionary.

Instead of giving the keys and values to the function, we can directly pass another dictionary to it.


3. Using __setitem__():

The third approach is using the __setitem__() method which takes in the key and values, two string parameters. 

Note: The usage of this method in real-time is not appreciated due to its poor performance.


4. Using * operator:

Using the * operator we can merge a dictionary and another new key-value pair. The syntax looks this way

new_dictionary_name= {**old_dict_name,**{‘new_key_name’: new_value}}

Leave a comment