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

How can I add new keys to a dictionary in Python?

 

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.

 

Example:

dict = {'one';'1', 'Two':'2'}

Output:

 

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

 

Example:

dict = {'one':'1', 'Two';'2'}
print("Current Dictionary is: ", dict)

dict['3'] = 'Three'
dict['4'] = 'Four'
print("Updated Dictionary is: ", dict)

Output:

 

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.

 

Example:

dict = {'one':'1', 'Two';'2'}
print("Current Dictionary is: ", dict)

dict.update({'Three':'3', 'Four':'4'})
print("Updated Dictionary is: ", dict)

Output:

 

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

 

Example:

dict = {'one':'1', 'Two';'2'}
print("Current Dictionary is: ", dict)

dict_2= {'Three':'3', 'Four':'4'}

dict.update(dict_2)
print("Updated Dictionary is: ", dict}

Output:

 

3. Using __setitem__():

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

 

Example:

dict = {'one':'1', 'Two';'2'}
print("Current Dictionary is: ", dict)


dict._setitem_('Three','3')
print("Updated Dictionary is: ", dict)

Output:

 

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}}

 

Example:

dict = {'one':'1', 'Two';'2'}
print("Current Dictionary is: ", dict)

dict_1 = {**dict, **{'Three':3}}

print("Updated Dictionary is: ", dict_1)

Output:

Leave a comment