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