How to Add a New Key to a Dictionary in Python?

Spread the love

Problem –

You want to add a new key to an existing dictionary.

Solution –

Let’s create a dictionary.

In [1]: person = {'Name': 'Noah', 'Age': 25, 'Location': 'New York'}

Now to add a new key in a dictionary, you have to give the name of the dictionary followed by the key in square brackets and new value in the right hand side of the equal sign.

To add the profession of Noah, you have to write

In [2]: person['Profession'] = 'Student'

In [3]: person
Out[3]: {'Name': 'Noah', 'Age': 25, 'Location': 'New York', 'Profession': 'Student'}

Related Posts –

  1. A Brief Introduction to Dictionaries in Python

Rating: 1 out of 5.

Leave a Reply