Skip to main content

How to add key-value pairs to a dictionary in Python

How to add key-value pairs to a dictionary in Python.

Here's a step-by-step tutorial on how to add key-value pairs to a dictionary in Python:

Step 1: Create an empty dictionary

To begin, you need to create an empty dictionary. You can do this by assigning an empty set of curly braces to a variable:

my_dict = {}

Step 2: Add key-value pairs using assignment

To add a key-value pair to the dictionary, you can use the assignment operator (=) to associate a value with a specific key. The key and value are separated by a colon (:), and the entire key-value pair is enclosed in curly braces {}.

my_dict = {}
my_dict['key1'] = 'value1'
my_dict['key2'] = 'value2'

In this example, we added two key-value pairs to the dictionary. The first pair has the key 'key1' and the value 'value1', and the second pair has the key 'key2' and the value 'value2'.

Step 3: Add key-value pairs using the update() method

Another way to add key-value pairs to a dictionary is by using the update() method. This method allows you to add multiple key-value pairs at once.

my_dict = {}
my_dict.update({'key1': 'value1', 'key2': 'value2'})

In this example, we added two key-value pairs to the dictionary using the update() method. The pairs are specified as a comma-separated list of key-value pairs enclosed in curly braces {}.

Step 4: Add key-value pairs using dictionary comprehension

In Python, you can also add key-value pairs to a dictionary using dictionary comprehension. This method is useful when you want to add multiple key-value pairs based on some condition or calculation.

my_dict = {x: x**2 for x in range(1, 5)}

In this example, we created a dictionary using dictionary comprehension. The key-value pairs are generated based on the values of x, which ranges from 1 to 4. The keys are the values of x, and the values are the squares of x.

Step 5: Add key-value pairs using the dict() constructor

The dict() constructor can also be used to add key-value pairs to a dictionary. You can pass a sequence of key-value pairs as arguments to the dict() constructor.

my_dict = dict([('key1', 'value1'), ('key2', 'value2')])

In this example, we passed a list of tuples containing the key-value pairs to the dict() constructor. The constructor converts the list of tuples into a dictionary.

That's it! You now know how to add key-value pairs to a dictionary in Python using different methods. Feel free to choose the method that best suits your needs.