How can I add new keys to a dictionary in Python

0 votes
Is it possible to add a key to a Python dictionary after it has been created?
Feb 9, 2022 in Python by Dev
• 6,000 points
328 views

1 answer to this question.

0 votes

Yes, it is possible to add new keys to a dictionary in Python, after creating a dictionary.
Let us take an example
1) To create a Dictionary
2) To add one single key to the dictionary
3) To add multiple keys to the dictionary

Data = {'Apple': 100, 'Orange' : 150 , 'Banana' : 155} #create a dictionary
Data

Output

{'Apple': 100, 'Orange': 150, 'Banana': 155}


Data['Cherry'] = 200 # updating or adding a single value in the dictionary
Data


Output

{'Apple': 100, 'Orange': 150, 'Banana': 155, 'Cherry': 200}


Data.update({'Cherry' : 250, 'Kiwi' : 140})  #updating multiple key
Data


Output



{'Apple': 100, 'Orange': 150, 'Banana': 155, 'Cherry': 250, 'Kiwi': 140}

Here, the value in Cherry gets updated and another Key named Kiwi is added. Thus, update helps to update and even to 

add keys to the dictionary.
Hope this helps!

answered Feb 9, 2022 by Nandini
• 5,480 points

Related Questions In Python

0 votes
1 answer

How can I add new keys to a dictionary?

d = {'key': 'value'} print(d) # {'key': 'value'} d['mynewkey'] = ...READ MORE

answered Dec 17, 2020 in Python by Gitika
• 65,910 points
438 views
0 votes
2 answers

How can I write a program to add two numbers using functions in python?

there is sum() function as a built ...READ MORE

answered Oct 25, 2020 in Python by anonymous
23,298 views
0 votes
3 answers

How to add a new item to a dictionary in Python?

There is no add() , append() , or insert() method ...READ MORE

answered Jan 4, 2021 in Python by Reshma
577 views
+2 votes
2 answers

How can I create a new file in Python?

You can try the below code which ...READ MORE

answered Mar 31, 2018 in Python by anto.trigg4
• 3,440 points
978 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,070 views
0 votes
1 answer
0 votes
1 answer

How can I count the occurrences of a list item?

For Counting the occurrences there are many ...READ MORE

answered Feb 7, 2022 in Python by Nandini
• 5,480 points
285 views
0 votes
1 answer

Is there a way to create multiline comments in Python?

In Python, you can use '''  some ...READ MORE

answered Feb 7, 2022 in Python by Nandini
• 5,480 points
266 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP