Built with Tutify.io

    AIStudyLabs

    Append Item to Dictionary in Python

    Append Item to Dictionary in Python

    How to append items or elements to a dictionary in Python? Python provides an update() method to append single or multiple items to the dictionary. The dictionary is mutable hence, you can easily append new elements to the dictionary. Note that items or elements are referred to same hence, I use them interchangeably.

    A Python dictionary is a collection that is unordered, mutable, and does not allow duplicates. Each element in the dictionary is in the form of key:value pairs. Dictionary elements should be enclosed with {} and key: value pair separated by commas. The dictionaries are indexed by keys.

    Using [] operator, update() and some more methods we can append the items to dictionaries very easily. In this article, I will explain by adding/updating elements how we can append the dictionary using multiple methods of dict of Python with examples.

    <a id="h-1-quick-examples-of-append-item-to-dictionary"></a>

    1. Quick Examples of Append Item to Dictionary

    Following are quick examples of how to append a single item or multiple items to a dictionary.

    
    # Quick examples of appending items to dictionary
    
    # Create a dictionary
    my_dict = {'course':'python','fee':4000}
    print("Original dictionary:", my_dict)
    
    # Example 1 : Using '[]' operator
    my_dict['tutor']='Richerd'
    
    # Example 2: Using append()
    # Appending multiple items to a dictionary
    my_dict.update({'tutor':'Richerd', 'duration':'45 days'})
    
    # Example 3: Using dict() constructor 
    my_dict = dict(my_dict, tutor = 'Richerd', duration = '45 days')
    
    # Example 4: Using ** operator append the dict
    new_dict = {**my_dict, **{'duration': '45 days'}}
    
    # Example 5: Create list of tuple key/value pairs
    # Using for loop to append key-value pair
    list = [('duration', '60 days'), ('tutor', 'Richerd')]
    for key, value in list:
        my_dict[key] = value
    
    # Example 6: Create a dictionary
    my_dict={'course': ['python', 'Pandas'], 
             'fee': 4000, 
             'duration': '60 days', 
             'tutor': 'Richerd'}
    
    # Using extend() method to append elements to list
    my_dict['course'].extend(['PySpark', 'Spark'])
    
    # Example 7: Append() method to append elements to list
    my_dict['course'].append('PySpark')
    

    2. Using [] to Append Item to Dictionary

    Using the '[]' operator we can append an item to the dictionary by assigning a value to the corresponding key. If the key doesn’t exist, the new key will be appended to the dictionary. If the key exists, it will be overwritten with a new key.

    
    # Create a dictionary
    my_dict = {'course':'python','fee':4000}
    print("Original dictionary:", my_dict)
    
    # Append element to a dictionary using '[]' operator
    my_dict['tutor']='Richerd'
    
    # Append element to a dictionary
    my_dict['duration']='45 days'
    print("New added dictionary:", my_dict)
    

    3. Using update() to Append Multiple Items

    To append multiple items or elements to the dictionary use the update() method. The update() method allows iterable sequence of key/value pair as an argument and appends its key-value pairs to the original dictionary. The update() method updates the values of existing keys with the new values it keys are already present.

    
    # Create dictionary
    my_dict = {'course':'python','fee':4000}
    print("Original dictionary:", my_dict)
    
    # Update multiple items to a dictionary
    my_dict.update({'tutor':'Richerd', 'duration':'45 days'})
    print("Updated dictionary:", my_dict)
    

    Yields below output.

    Using update() method we can update the values of existing keys with the new values. Let's take an example,

    
    # Create dictionary
    my_dict = {'course':'python','fee':4000}
    print("Original dictionary:", my_dict)
    
    # Overwrites the values of existing keys 
    # with new values using update()  
    my_dict.update({'fee':5000, 'duration':'45 days'})
    print("Updated dictionary:", my_dict)
    
    # Output:
    # Original dictionary: {'course': 'python', 'fee': 4000}
    # Updated dictionary: {'course': 'python', 'fee': 5000, 'duration': '45 days'}
    

    <a id="h-4-using-python-dict-to-append-to-dictionary"></a>

    4. Using Python dict() to Append to Dictionary

    Using the dict() constructor, we can create dictionaries and it can also be used to append elements to the dictionary by merging the existing dictionary with the new elements. This returns a new dictionary with all the elements.

    
    # Append the dictionary using dict() constructor 
    my_dict = dict(my_dict, tutor = 'Richerd', duration = '45 days')
    print("Appended dictionary:\n", my_dict)
    
    # Output:
    # Appended dictionary: 
    # {'course': 'python', 'fee': 4000, 'duration': '60 days', 'tutor': 'Richerd'}
    

    <a id="h-5-python-dictionary-append-using-operator"></a>

    5. Python Dictionary Append using ** Operator

    Alternatively, We can append a dictionary by merging the given dictionary and key/value pair(which we want to append to a dictionary) in another dictionary using ** operator. It will append the key/value pair to the given dictionary.

    
    # Using ** operator append the dict
    new_dict = {**my_dict, **{'duration': '45 days'}}
    print("New dictionary\n:", new_dict)
    
    # Output:
    # New dictionary:
    # {'course': 'python', 'fee': 4000, 'duration': '45 days'}
    

    6. Append Python Dict using For Loop

    Take specified key/value pairs as a list of tuples and then iterate each key/value pair using for loop. Finally, append each key/value pair to the given dictionary.

    
    # Create list of tuple key/value pairs
    list = [('duration', '60 days'), ('tutor', 'Richerd')]
    
    # Using for loop to append key-value pair
    for key, value in list:
        my_dict[key] = value
    print("Appended dictionary:", my_dict)
    
    # Output:
    # Appended dictionary: {'course': 'python', 'fee': 4000, 'duration': 
    # '60 days', 'tutor': 'Richerd'}
    

    <a id="h-7-using-extend-method-append-dictionary"></a>

    7. Using extend() Method Append Dictionary

    So far, we have learned how to append dictionaries with key/value pairs. Same like this we will learn how to append more values to the existing key of the Dict. We know that dictionary value can be any data type such as a number(int, float), a string, a list, a tuple, or even another dictionary.

    extend() method is an in-built method of Python list using this method we can append the dictionary by appending more values(in the form of a list) to the existing key.

    
    # Create a dictionary
    my_dict={'course': ['python', 'Pandas'], 'fee': 4000, 'duration': '60 days', 'tutor': 'Richerd'}
    print("Original dictionary:\n", my_dict)
    
    # Using extend() method to append elements to list
    my_dict['course'].extend(['PySpark', 'Spark'])
    print("Appended dictionary:\n", my_dict)
    
    # Output: 
    # Original dictionary:
    # {'course': ['python', 'Pandas'], 'fee': 4000, 'duration': 
    # '60 days', 'tutor': 'Richerd'}
    # Appended dictionary:
    # {'course': ['python', 'Pandas', 'PySpark', 'Spark'], 
    # 'fee': 4000, 'duration': '60 days', 'tutor': 'Richerd'}
    

    8. Append Elements to Values

    When dict key has a list of values and we want to append more values to the list, we can use append(), it is a list method in Python. Let's append more values to the list using append() method.

    
    # Create a dictionary
    my_dict={'course': ['python', 'Pandas'], 'fee': 4000, 'duration': '60 days', 'tutor': 'Richerd'}
    print("Original dictionary:\n", my_dict)
    
    # Using append() method to append elements to list
    my_dict['course'].append('PySpark')
    print("Appended Dictionary:\n", my_dict)
    
    # Output:
    # Original dictionary:
    # {'course': ['python', 'Pandas'], 'fee': 4000, 'duration': 
    # '60 days', 'tutor': 'Richerd'}
    # Appended Dictionary:
    # {'course': ['python', 'Pandas', 'PySpark'], 'fee': 4000, 
    # 'duration': '60 days', 'tutor': 'Richerd'}
    

    <a id="h-9-conclusion"></a>

    9. Conclusion

    In this article, I have explained how to append an item or element to a Python dictionary using various methods and operators. And also explained using extend() and append() methods how we can add more values to the existing key of Python dict with examples.

    Happy Learning !!

    <a id="h-related-articles"></a>

    Related Articles