Q&A

Questions &
Answers with MarsDevs

HTML & CSS
JavaScript

How can I add new keys to a dictionary?

Solution:

You can add new keys to a dictionary in Python by assigning a value to a new key using the square bracket notation. Let’s see some examples.


     #Creating an empty dictionary 
     my_dict = {}

     #Adding new keys and their corresponding values
     my_dict['key1'] = 'value1'
     my_dict['key2'] = 42
     my_dict['key3'] = [1, 2, 3]

     print(my_dict)

In this example, an empty dictionary my_dict is created, and then new keys 'key1', 'key2', and 'key3' are added along with their respective values. 

The output will be:

{'key1': 'value1', 'key2': 42, 'key3': [1, 2, 3]}

However, you can use the update() method to add multiple key-value pairs.


#Adding multiple key-value pairs
my_dict.update({'key4': 'value4', 'key5': 3.14})

print(my_dict)

The output:

{'key1': 'value1', 'key2': 42, 'key3': [1, 2, 3], 'key4': 'value4', 'key5': 3.14}

Continue your learning with more such Python blogs from MarsDevs!