Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Python by (1.6k points)

I want to add an item to an existing dictionary in python. For example, this is my dictionary:

default_data = {

            'item1': 1,

            'item2': 2,

}

I want to add new item such that:

default_data = default_data + {'item3':3}

How to achieve this?

3 Answers

0 votes
by (25.1k points)

You can do it simply by setting the key 'item3' to value 3 like this:

default_data["item3"] = 3

or if you want to insert multiple items at one you can do it like this:

default_data.update({"item3": 3, "item4": 4})

0 votes
by (20.3k points)

Try using the code given below:

default_data['item3'] = 3

Easy as py, Or else you can use the below code:

default_data.update({'item3': 3})

And it's applicable for inserting multiple items at once.

0 votes
by (106k points)

To add new items to dictionary you can use the below-mentioned code:-

>>> class Dict(dict): 

... def __add__(self, other):

... copy = self.copy() 

... copy.update(other) 

... return copy 

... def __radd__(self, other):

... copy = other.copy()

... copy.update(self)

... return copy 

... 

>>> default_data = Dict({'item1': 1, 'item2': 2}) 

>>> default_data + {'item3': 3} 

{'item2': 2, 'item3': 3, 'item1': 1} 

>>> {'test1': 1} + Dict(test2=2) 

{'test1': 1, 'test2': 2}

Related questions

0 votes
1 answer
0 votes
1 answer
asked Sep 17, 2019 in Python by Sammy (47.6k points)
+1 vote
1 answer
asked May 24, 2019 in Python by Anvi (10.2k points)
0 votes
1 answer
0 votes
1 answer
asked Aug 27, 2019 in Python by Sammy (47.6k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94.2k users

Browse Categories

...