A dictionary in Python is a collection of key-value pairs. Each key is unique, and it maps to a specific value. Think of it as a real-world dictionary where a word (key) maps to its definition (value).

How to Append to a Dictionary in Python?

1. Appending to a Dictionary

Appending to a dictionary means adding a new key-value pair or updating an existing key with a new value. Here's how you can do it:

2. Adding a New Key-Value Pair

You can add a new key-value pair to a dictionary using the assignment operator =. If the key does not exist in the dictionary, a new entry is created.

my_dict = {'name': 'Alice', 'age': 25}
my_dict['city'] = 'New York'
print(my_dict)

Output:

{'name': 'Alice', 'age': 25, 'city': 'New York'}

3. Updating an Existing Key

If the key already exists in the dictionary, assigning a new value to that key will update the existing value.

my_dict['age'] = 26
print(my_dict)

Output:

{'name': 'Alice', 'age': 26, 'city': 'New York'}

4. Using the update() Method

The update() method can add multiple key-value pairs to a dictionary or update multiple keys at once.

my_dict.update({'country': 'USA', 'age': 27})
print(my_dict)

Output:

{'name': 'Alice', 'age': 27, 'city': 'New York', 'country': 'USA'}

Conclusion

Appending to a dictionary in Python is straightforward. You can add a new key-value pair by assigning a value to a new key or update an existing key by assigning a new value to it. The update() method allows for adding or updating multiple key-value pairs at once. By understanding these simple methods, you can easily manage and manipulate dictionaries in Python.

Simon

102 Articles

I love talking about tech.