search

How to add items to a dictionary in Python?

In Python, you can add items to a dictionary by assigning a value to a new or existing key. Here are a few ways to add items to a dictionary:

Square Bracket Notation:

my_dict = {'name': 'John', 'age': 30}

# Add a new key-value pair
my_dict['city'] = 'New York'

update() Method:

my_dict = {'name': 'John', 'age': 30}

# Add a new key-value pair
my_dict.update({'city': 'New York'})
# or
my_dict.update(city='New York')

Using dict() Function:

my_dict = {'name': 'John', 'age': 30}

# Add a new key-value pair
my_dict = dict(my_dict, city='New York')

In the above examples, a new key-value pair is added to the dictionary. If the key already exists, assigning a new value to it will update the existing value. If the key doesn't exist, a new key-value pair will be created.

After adding the items, the dictionary will look like this:

{'name': 'John', 'age': 30, 'city': 'New York'}

You can also use variables to dynamically add items to a dictionary:

my_dict = {}
key = 'name'
value = 'John'

my_dict[key] = value

In this case, the value of the key variable becomes the new key, and the value of the value variable becomes the associated value.

Adding items to a dictionary allows you to dynamically update and expand the dictionary's contents. You can add as many key-value pairs as needed to represent your data accurately.

Related Questions You Might Be Interested