How To Add To A Dictionary Python
Last Updated : Mar 11, 2024
In this article we will show you the solution of how to add to a dictionary python, a dictionary is one of the built-in Python data types. In dictionary terminology, a key-value pair represents a sequence of values.
Dictionary keys must be unique within each dictionary and are immutable within dictionaries, even though dictionaries are mutable objects.
The dictionary does not have a built-in method for adding to or updating it, but there are several ways to do so.
As the title suggests, this article covers adding to and updating Python dictionaries using the assignment operator, the update() method, and the merge and update dictionary operators.
We will now discuss the idea of how to add to a dictionary in python with an example.
Step By Step Guide On How To Add To A Dictionary Python :-
class my_dict(dict): # __init__ function def __init__(self): self = dict() # Function to add key:value def add(self, keys, values): self[keys] = values # Main Function dict_objct = my_dict() dict_objct.keys = input("Enter a key : ") dict_objct.values = input("Enter a value : ") dict_objct.add(dict_objct.keys, dict_objct.values) dict_objct.add("Amruta", 24) print(dict_objct)
- In this example, we define a class called my_dict, which inherits from the built-in class dict. An init method creates a dictionary instance, while an add method adds key-value pairs to it. In this class there are two methods: init and add.
- By assigning an empty dictionary instance to the dictionary instance in the init method, we initialize the dictionary instance.
- A new key:value pair is added to the dictionary instance using the add method, which takes two arguments keys and values.
- In the next step, we create a class instance of dict_object, which is part of the my_dict class.
- Users can fill out the input function by entering the key and value they want to add to the dictionary.
- Using the key and value that were inputted by the user, we call the add method on the dict_object instance.
- The Dictionary is then expanded using the .add() method to include yet another pair of key:values.
- After printing the contents of the dict_objct dictionary, we return to the previous line.
Conclusion :-
As a result, we have successfully learned how to add to a dictionary in python with an example.
The Python language very frequently uses dictionaries for storing data and providing quick access by using a unique key value.
Using these identifiers is useful for accessing data in lists or tuples where we need to refer to it by its specific identifier rather than by its sequence number.
I hope this article on how to add to a dictionary python helps you and the steps and method mentioned above are easy to follow and implement.