Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a new item to a dictionary in Python [duplicate]

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 a new item such that:

default_data = default_data + {'item3':3} 

How can I achieve this?

like image 255
brsbilgic Avatar asked Jun 20 '11 19:06

brsbilgic


People also ask

Can we add duplicate values in dictionary Python?

The straight answer is NO. You can not have duplicate keys in a dictionary in Python.

Can we add duplicate values in dictionary?

[C#] Dictionary with duplicate keys The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.

How do I add an item to a dictionary in Python?

There is no add() , append() , or insert() method you can use to add an item to a dictionary in Python. Instead, you add an item to a dictionary by inserting a new index key into the dictionary, then assigning it a particular value.


1 Answers

default_data['item3'] = 3 

Easy as py.

Another possible solution:

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

which is nice if you want to insert multiple items at once.

like image 91
Chris Eberle Avatar answered Oct 08 '22 13:10

Chris Eberle