Python Program to Add Elements to a Dictionary
A dictionary is a data structure that is widely used in Python programming. It represents a collection of key-value pairs where each key is unique and can be used to access its corresponding value efficiently. In this article, we will discuss how to add elements to a dictionary using Python.
Creating a Dictionary
Before we learn how to add elements to a dictionary, let’s first understand how to create a dictionary in Python. A dictionary can be created using curly braces {} and assigning key-value pairs to it. The code below shows how to create a dictionary with a key of "apple" and a value of "red".
my_dict = {"apple": "red"}
Adding a New Key-Value Pair to a Dictionary
To add a new key-value pair to an existing dictionary in Python, we can use the square bracket notation to assign a value to a new key. The code below shows how to add a new key-value pair of "banana" and "yellow" to the dictionary.
my_dict["banana"] = "yellow"
The code above will add a new key "banana" and set its value to "yellow".
Updating an Existing Key-Value Pair in a Dictionary
If a key already exists in a dictionary, we can update its value by assigning a new value to that key using the square bracket notation. The code below shows how to update the value of the "apple" key from "red" to "green".
my_dict["apple"] = "green"
The code above will update the value of the existing key "apple" from "red" to "green".
Merging Two Dictionaries
We can also merge two dictionaries together by using the update() method. The code below shows how to merge two dictionaries "dict1" and "dict2" into the "dict1" dictionary.
dict1 = {"apple": "red", "banana": "yellow"}
dict2 = {"orange": "orange", "grape": "purple"}
dict1.update(dict2)
The update() method will add all the key-value pairs from "dict2" into "dict1". If "dict1" already contains a key-value pair that is also in "dict2", the value in "dict1" will be updated to the value in "dict2".
Conclusion
In this article, we learned how to add new elements to a dictionary in Python. We also learned how to update the value of an existing key-value pair and how to merge two dictionaries together. Dictionaries are a powerful way to store data in Python, and understanding how to manipulate them is a critical skill in Python programming.