How To Add A Key To A Dictionary Python

In this tutorial, we will learn how to add a key to a dictionary in Python. Dictionaries are an important data structure in Python that allows users to store key-value pairs. We’ll cover the basics of dictionaries, how to create them, and most importantly, how to add new keys to an existing dictionary.

Before we dive into the steps, let’s briefly talk about dictionaries in Python. A dictionary is created using curly brackets {} and contains keys and values separated by colons. The keys can be any hashable data type, like strings, numbers, or tuples. The values, on the other hand, can be of any data type.

Let’s start with adding a key to a dictionary in Python.

Step 1: Create a simple dictionary in Python

To create a dictionary, you can simply create an empty dictionary using the {} notation or initialize it with some key-value pairs. In this tutorial, let’s work with the following dictionary.

Step 2: Add a key-value pair to the dictionary

To add a new key-value pair to the dictionary, you can simply use the following syntax:

For our example, let’s add the employee’s department to our employee dictionary.

Now, the employee dictionary has the added department key with the value ‘HR’.

{'name': 'John', 'age': 30, 'city': 'Chicago', 'department': 'HR'}

Step 3: Update the value of an existing key

If you want to update the value of an existing key in the dictionary, you can follow the same syntax as adding a key. Keep in mind that if the specified key does not exist in the dictionary, a new key-value pair will be added. If the key already exists, its value will be updated.

In this case, we’re updating the age of our employees from 30 to 31.

{'name': 'John', 'age': 31, 'city': 'Chicago', 'department': 'HR'}

Full code

Conclusion

In this tutorial, we learned how to add a key to a dictionary in Python. We started by creating a simple dictionary, then added a new key-value pair, and finally updated the value of an existing key. This is an essential skill for working with dictionaries in Python, as they provide a versatile and efficient way to store and manipulate data.