Python Tutorials
Basic

Data Structure and Data Types

String

List

Tuple

Set

Dictionary

Functions / Methods

Advance

Exception Handling

Python Add Dictionary Items


Add Dictionary Items

You can add a new item to the dictionary by simply enclosing the key in square brackets with the dictionary variable name and assigning value to that key.

Example
company_dictionary = {
    "name": "Google", 
    "country": "USA", 
    "start_year": 1995
}

company_dictionary["sector"] = "Private"
print(company_dictionary)
{'name': 'Google', 'country': 'USA', 'start_year': 1995, 'sector': 'Private'}

In the above example, we added the new item to the company_dictionary by putting the key name ("sector") in a square bracket and assigning a value ("Private") to them.


Update Dictionary

Using the update() function, you can update the existing dictionary item value or add a new item to the dictionary.

The update() function accepts input param as a key-value pair dictionary.

Example
company_dictionary = {
    "name": "Google", 
    "country": "USA", 
    "start_year": 1995
}

company_dictionary.update({"start_year": 2000, "sector": "Private"})
print(company_dictionary)
{'name': 'Google', 'country': 'USA', 'start_year': 2000, 'sector': 'Private'}

In the above example, we are updating the company_dictionary start_year item value and adding a new item.

Here, in the output, you can see the start_year of the company_dictionary new value is 2000 and sector is "Private".