Working with dictionaries in Python is one of the most important tasks you’ll need to master if you want to effectively use this popular programming language.
Dictionaries allow us to store data in key-value pairs and provide many flexible ways to access and manipulate this data. In this tutorial, we will guide you on how to add a field in a dictionary in Python.
Step 1: Create Your Python Dictionary
To add a field to a dictionary, we first need a dictionary. In Python, a dictionary can be created using the curly brackets {}. Let’s create a simple dictionary named ‘student’.
1 2 3 4 5 |
student = { 'name': 'John Doe', 'age': 22, 'course': 'Computer Science' } |
Step 2: Adding a New Field
To add a new field in a dictionary in Python, the syntax is straightforward. You simply refer to the dictionary with the new key as the index and assign the value to it.
1 |
student['grade'] = 'A' |
When we print the dictionary now, it should include the new ‘grade’ field that we just added.
Step 3: Print the Modified Dictionary
Let’s print out our dictionary to confirm that the new field has been added.
1 |
print(student) |
You can find more about the dictionary on Python’s official tutorial.
The Full Code:
1 2 3 4 5 6 7 8 9 |
student = { 'name': 'John Doe', 'age': 22, 'course': 'Computer Science' } student['grade'] = 'A' print(student) |
The Output:
{'name': 'John Doe', 'age': 22, 'course': 'Computer Science', 'grade': 'A'}
Conclusion
The ability to add fields to a dictionary is one of the many reasons why dictionaries are so powerful and flexible in Python. As you can see, adding a new key-value pair is a simple one-step process. This characteristic of dictionaries is one of many that has helped Python become one of the most popular and widely used programming languages in the world today.