Python Dictionary Append: How to Add Elements in a Python Dictionary?

Posted in /  

Python Dictionary Append: How to Add Elements in a Python Dictionary?
vinaykhatri

Vinay Khatri
Last updated on April 24, 2024

    Python dictionary is one of the most important and widely used Python data structures. Unlike other Python data types such as list, string, tuple, and set, the Python dictionary stores its elements in key-value pairs. Every key-value pair in the dictionary is separated using a comma (,) and every key and its respective value are separated with a colon (:). Also, all the keys and values of a dictionary are stored using the curly brackets {key1:value1, key2:value2} . A Python dictionary Key can only be an immutable data type such as string, integer, and tuple. On the other hand, the Value could be of any data type. In this Python tutorial, we will go through the different techniques to append new elements or key:value pairs in a Python dictionary. By the end of this article, you will understand how to add key:value pairs in a Python dictionary.

    How to Append a New "Key:Value" in a Python Dictionary?

    Unfortunately, the dictionary in Python does not come with an inbuilt append() method like a list. However, there are different techniques to add a new element in a Python dictionary that are as follows:

    • Python dictionary update() method.
    • Add new elements using a square bracket or subscript notation.
    • Python dictionary __setitem__ method.
    • Using **kwargs.

    These are the most common and straightforward techniques to add new key:value pair in a dictionary. Let's now discuss each technique separately.

    • Add new key:value pair in a Python dictionary with update() method

    update() is a Python dictionary method, which is generally used to update the existing key:value pair of a dictionary but it can also be used to add a new key:value element in the dictionary. Python dictionary update() syntax:

    dictionary.update(dict)

    Parameter The update(dict) method accepts only one argument of dict type. It adds that dict element to the dictionary if the element is not present in the dictionary. Else it just updates the value for the key, which is already present in the dictionary. Python dictionary update() Example 1:

    my_dict1 = {"1":"one", "2":"Two"}
    
    my_dict2 = {"3": "Three", "4":"Four"}
    
    #add my_dict2 in my_dict1
    my_dict1.update(my_dict2)
    
    print("The value of my_dict1 is:", my_dict1)
    print("The value of my_dict2 is:", my_dict2)

    Output

    The value of my_dict1 is: {'1': 'one', '2': 'Two', '3': 'Three', '4': 'Four'}
    The value of my_dict2 is: {'3': 'Three', '4': 'Four'}

    In the above example, you can see that the update() method add the my_dict2 dictionary elements at the end of my_dict1 dictionary. But if the my_dict2 would have a similar key to the my_dict1 dictionary, then instead of adding, the update() method would update the value of the key in my_dict1 . And this makes sense too because a key in a dictionary cannot have two different values. Python dictionary update() Example 2:

    my_dict1 = {"1":"one", "2":"Two"}
    
    my_dict2 = {"3": "Three", "1":"One"}
    
    #add 3 update 1
    my_dict1.update(my_dict2)
    
    print("The value of my_dict1 is:", my_dict1)
    print("The value of my_dict2 is:", my_dict2)

    Output

    The value of my_dict1 is: {'1': 'One', '2': 'Two', '3': 'Three'}
    The value of my_dict2 is: {'3': 'Three', '1': 'One'}

    In the above example, the dictionary update() method add "4":"Four" key/value pair in my_dict1 but update the "1":"One" pair. This is because the key to "1" already exists in the dictionary my_dict1.

    • Add new key:value pair in a Python dictionary with Subscript Notation or square bracket

    Similar to the Python list, the Python dictionary can also use square brackets or subscript notation to access and update the value for the specified key. Moreover, by using the subscript notation or square bracket, we can also add a new key-value pair to a Python dictionary. This is the most common and widely used technique for adding a new key-value pair in the dictionary. However, this technique allows us to add only a single key-value pair to the dictionary. To add multiple key-value pairs to the dictionary, we have to use the dictionary update() method. Syntax

    dictionary[new_key] = value

    It will add new_key-value pair to the dictionary only if the new_key is not present in the dictionary, else it would just assign the value to the new_key. Example

    my_dict = {"1":"one", "2":"Two"}
    
    #add new key:value
    my_dict["3"] ="Three"
    
    print("The value of my_dict is:", my_dict)
    

    Output

    The value of my_dict is: {'1': 'one', '2': 'Two', '3': 'Three'}
    
    • Add new key:value pair in a Python dictionary with __setitem__() method

    Python dictionary also has __setitem__() dunder method that can add new key:value pair in a dictionary. While coding in Python, you will not be using this technique to add elements in a Python dictionary because of its low performance and inefficiency. But it's good to know all the available options to append a new element in a dictionary. Python dictionary __setitem__() syntax

    dictionary.__setitem__(new_key, value)

    The __setitem__(key, value) method accepts two arguments - key and value. Like update() method, it will add the specified key:value pair to the dictionary if the dictionary already does not have the specified key. Else it will just update the value for the specified key . Example

    my_dict = {"1":"one", "2":"Two"}
    
    #add new key:value
    my_dict.__setitem__("3", "Three")
    
    #update old key:value
    my_dict.__setitem__("1", "One")
    
    print("The value of my_dict is:", my_dict)

    Output

    The value of my_dict is: {'1': 'One', '2': 'Two', '3': 'Three'}
    • Add new key:value pair in a Python dictionary with ** operator

    If we use two stars (**) before any variable, it represents the key-value pair . The ** operator often used to represent Python **kwargs or keyword arguments. Using the Python ** operator we can merge two dictionaries or add a new element to a dictionary. Syntax

    dictionary = {**dict1, **dict2}

    Example

    my_dict = {"1":"one", "2":"Two"}
    
    #add 3 and update 1
    my_dict = {**my_dict, **{"3": "Three"}, **{"1":"One"}}
    
    print("The value of my_dict is:", my_dict)

    Output

    The value of my_dict is: {'1': 'One', '2': 'Two', '3': 'Three'}
    

    Conclusion

    In this Python tutorial, you learned how to add or append a new element or key:value pair in a Python dictionary. Generally, you will be using the Subscript notation or square bracket to add a new element in a dictionary. In rare cases, you will be using the Python dictionary update() and __setitem__() methods. If you wish to merge two or more dictionaries, you should use the ** operator. People are also reading:

    Leave a Comment on this Post

    0 Comments