How To Append To A Dictionary In Python

One of the most common data structures in Python is the dictionary. A dictionary is an unordered collection of key-value pairs, where each key must be unique. In this blog post, we’ll discuss how to append (add) key-value pairs to an existing dictionary in Python.

Appending to a Dictionary

There is no built-in “append” method for dictionaries in Python, but you can easily add new key-value pairs by using the following syntax:

dictionary[key] = value

Here’s an example of how to append to a dictionary in Python:

    # Create a dictionary with some initial key-value pairs
    person = {
        'name': 'John Doe',
        'age': 30,
        'city': 'New York'
    }

    # Append a new key-value pair to the dictionary
    person['country'] = 'USA'

    # Print the updated dictionary
    print(person)
    

The output of this code would be:

{‘name’: ‘John Doe’, ‘age’: 30, ‘city’: ‘New York’, ‘country’: ‘USA’}

Appending to a Dictionary Using the update() Method

Another way to append to a dictionary is by using the update() method. This method takes a dictionary as its argument and adds its key-value pairs to the calling dictionary. If the calling dictionary already has a key that is present in the given dictionary, its value will be updated with the value from the given dictionary.

Here’s an example of how to use the update() method to append to a dictionary in Python:

    # Create two dictionaries
    person = {
        'name': 'John Doe',
        'age': 30,
        'city': 'New York'
    }

    extra_info = {
        'country': 'USA',
        'occupation': 'Software Developer'
    }

    # Append the key-value pairs from extra_info to person
    person.update(extra_info)

    # Print the updated dictionary
    print(person)
    

The output of this code would be:

{‘name’: ‘John Doe’, ‘age’: 30, ‘city’: ‘New York’, ‘country’: ‘USA’, ‘occupation’: ‘Software Developer’}

Conclusion

In this blog post, we’ve shown you two ways to append key-value pairs to an existing dictionary in Python. You can either use the dictionary[key] = value syntax to add individual key-value pairs, or you can use the update() method to merge two dictionaries.