Add() Method in Python Dictionary

This tutorial will discuss how to create an add() method for Dictionary in Python.

The Python dictionary does not provide a direct add() method to add a new key-value pair to the dictionary, so we decided to create one.

This is the add() method.

def add_to_dictionary(dictionary, key, value):
    # Custom add method to add or update a key-value
    # pair in a dictionary.
    #
    # Args:
    #    dictionary (dict):  The dictionary to which the key-value
    #                        pair will be added or updated.
    #    key: The key for the key-value pair.
    #    value: The value for the key-value pair.
    #
    # Returns:
    #    None
    dictionary[key] = value

It expects three arguments: first is a dictionary, second is the key that needs to be added, and the third parameter is the value that will be linked with that key. So internally, it will use square brackets to add the key-value pair into the dictionary.

Let’s use this method. First of all, we will create an empty dictionary,

my_dict = {}

Then we can add a new key-value pair into the dictionary using this add() method.

# Add two key-value pairs to dictionary
add_to_dictionary(my_dict, "key1", "value1")
add_to_dictionary(my_dict, "key2", "value2")

If we print the dictionary, it will contain the key-value pairs.

Let’s see the complete example,

def add_to_dictionary(dictionary, key, value):
    # Custom add method to add or update a key-value
    # pair in a dictionary.
    #
    # Args:
    #    dictionary (dict):  The dictionary to which the key-value
    #                        pair will be added or updated.
    #    key: The key for the key-value pair.
    #    value: The value for the key-value pair.
    #
    # Returns:
    #    None
    dictionary[key] = value

# create an empty dictionary
my_dict = {}

# Add two key-value pairs to dictionary
add_to_dictionary(my_dict, "key1", "value1")
add_to_dictionary(my_dict, "key2", "value2")

print(my_dict)

Output

{'key1': 'value1', 'key2': 'value2'}

Summary

Today, we learned how to add() method in Python dictionary.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top