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.
1 |
employee = {'name': 'John', 'age': 30, 'city': 'Chicago'} |
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:
1 |
dictionary[key] = value |
For our example, let’s add the employee’s department to our employee
dictionary.
1 |
employee['department'] = 'HR' |
Now, the employee
dictionary has the added department
key with the value ‘HR’.
1 |
print(employee) |
{'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.
1 |
employee['age'] = 31 |
In this case, we’re updating the age of our employees from 30 to 31.
1 |
print(employee) |
{'name': 'John', 'age': 31, 'city': 'Chicago', 'department': 'HR'}
Full code
1 2 3 4 5 6 7 |
employee = {'name': 'John', 'age': 30, 'city': 'Chicago'} employee['department'] = 'HR' print(employee) employee['age'] = 31 print(employee) |
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.