In Python, dictionaries are mutable, which means you can add new elements or update existing ones easily. Let’s explore different methods to add elements to a dictionary.
Method 1: Using Square Brackets
# Method 1: Using Square Brackets my_dict = {"name": "John", "age": 30} my_dict["city"] = "New York" print(my_dict)
Output:
{‘name’: ‘John’, ‘age’: 30, ‘city’: ‘New York’}
Method 2: Using the update() Method
# Method 2: Using the update() Method my_dict = {"name": "John", "age": 30} my_dict.update({"city": "New York"}) print(my_dict)
Output:
{‘name’: ‘John’, ‘age’: 30, ‘city’: ‘New York’}