Add a new item to a dictionary in Python

brsbilgic picture brsbilgic · Jun 20, 2011 · Viewed 1.6M times · Source

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?

Answer

Chris Eberle picture Chris Eberle · Jun 20, 2011
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.