Python Tutorial

Changing or Adding Elements in Python Dictionary

How to Add an Element in Python Dictionary?

You can change or add elements in a dictionary in Python.  By creating a new index key and providing a value to it, you can add an item to the dictionary.

Example:

thisdict = {

  "brand": "Ford",

  "model": "Mustang",

  "year": 1964

}

thisdict["color"] = "red"

print(thisdict)

Output:

{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}

How to Update an Element in Python Dictionary?

The dictionary will be updated with items from a provided input using the update() method. If the object does not already exist, it will be created.

A dictionary or an iterable object containing key-value pairs must be used as the argument.

Example:

thisdict = {

  "brand": "Ford",

  "model": "Mustang",

  "year": 1964

}

thisdict.update({"color": "red"})

Output:

{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}

Video : https://youtu.be/xhjdfmu0FVA

Did you find this article helpful?