In Python dictionaries, you don’t use the term “append” like you would with lists. Instead, you add a new key-value pair to a dictionary. Here’s how you can add key-value pairs to a dictionary, along with a description:
Adding a Key-Value Pair to a Dictionary:
You can add a new key-value pair to a dictionary using the following syntax:
my_dict[key] = value
Here’s a brief description:
my_dict
: The name of the dictionary to which you want to add a key-value pair.key
: The key you want to add or update.value
: The value associated with the key.
Example:
# Creating an empty dictionary
person_info = {}
# Adding key-value pairs
person_info['name'] = 'John'
person_info['age'] = 25
person_info['city'] = 'New York'
In this example:
- Initially,
person_info
is an empty dictionary. - The
['name'] = 'John'
line adds a key-value pair where the key is ‘name’ and the value is ‘John’. - Similarly, the next two lines add key-value pairs for ‘age’ and ‘city’.
Now, person_info
looks like this:
{
'name': 'John',
'age': 25,
'city': 'New York'
}
Updating an Existing Key:
If the key already exists in the dictionary, assigning a new value to that key will update its value:
# Updating the 'age' key
person_info['age'] = 26
Now, person_info
will be:
{
'name': 'John',
'age': 26,
'city': 'New York'
}
Adding key-value pairs is a fundamental operation when working with dictionaries in Python. It allows you to dynamically build and modify data structures based on your program’s needs.