Search code snippets, questions, articles...

Add items to dictionary in python

We can add a new item to the dictionary by creating a new key and assigning some value to it.
# Define new dictionary
subject = {
    'name': 'Math',
    'marks': '100'

# Add new item to dictionary
subject['code'] = 'M01'

# -> {'name': 'Math', 'marks': '100', 'code': 'M01'}
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place.

To add an item to the dictionary, you just have to assign the relevant data to the relevant key in a dictionary. This is done by enclosing the key and value in braces.

In the above code snippet

1. We have created a dictionary named subject that contains multiple items.

2. We have created a new key 'code' and assigned a value 'M01' to it.

3. Print the dictionary(subject).

If the key already exists inside the dictionary then its value will be updated.

# Define new dictionary
subject = {
    'name': 'English',
    'marks': '50'

# Add new item using update() function
subject.update({'code': 'E01'})

# -> {'name': 'English', 'marks': '50', 'code': 'E01'}
We are using update() function to add new key-value pair in the dictionary(subject). We have added code key and assigned a value E01 to it
Was this helpful?