pythondictionaryitems

Add a new item to a dictionary in Python


How do I add an item to an existing dictionary in Python? For example, given:

default_data = {
    'item1': 1,
    'item2': 2,
}

I want to add a new item such that:

default_data = default_data + {'item3': 3}

Solution

  • 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.