How to Add an Item to a Python Dictionary with update()
This Snippet is coded by a user inOnline python Compiler. You can see and run this code too.
زبان: python
In Python, dictionaries are mutable data structures that store key-value pairs. To add a new item (key-value pair) to a dictionary, you can use the update() method.
The update() method accepts a dictionary (or an iterable of key-value pairs) and adds each key-value pair to the original dictionary. If a key already exists, its value is updated; otherwise, a new key is added.
Example:
car = {"brand": "Ford", "model": "Mustang", "year": 1964}
car.update({"color": "White"})
print(car) # Output: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'White'}In this example, the dictionary car initially has three items. The update() method adds the new key "color" with value "White". Alternatively, you can also assign directly: car["color"] = "White", but update() is useful for adding multiple items at once.