Write Python Program to Add Key to Dictionary

Write a python program to add a key to a dictionary is provided on this page.

Write A Python Program To Add A Key To A Dictionary

Adding a new key in dictionary is very easy.


dictionary = {"first name" : "john"}
  
dictionary["last name"] = "cena"
  
print(dictionary)

Output

{'first name': 'john', 'last name': 'cena'}

As you can see, to add new key to dictionary we need to write key name inside square brackets and set the value.

If we don't know the value we can set any dummy value like "" or None.

There is one other way to add key to dictionary, using update() method on dictionary object.


dictionary = {"first name" : "john"}
  
dictionary.update({"last name", "cena"})
  
print(dictionary)

Here output will be same as before.

This method takes a dictinary iteself as input.

It will then add the keys of input dictionary to the dictionary on which its called. Ofcourse it will also add respective values.

Related To Python

Comments