In this article, we will learn how to create a 2D or two-dimensional dictionary using Python. The same technique can be used to create an n-dimensional dictionary using Python.
Let’s take a practical scenario, of a two-dimensional database. Each Database has a primary key student_id and other entries such as student_name, student_first_name, student_last_name, student_department, student_major, student_graduation_year
So, for this example, we will create 5 student records using a 2D Dictionary with an order of 5×6. We will also update two records that will help you to learn how to read and write elements to your 2-dimensional dictionary.
Python Code to create and add items to 2D dictionary
dictionary_fields = {'first_name': ' ', 'last_name': ' ', 'dept': ' ', 'major': ' ', 'year': ' ' }
student_id = [1, 2, 3, 4, 5]
student_record = {}
#To create 5 records: We will run loop for 5 times
for i in range(0, 5):
student_record.update({student_id[i]: dict(dictionary_fields)})
#Add two items to 2D dictionary
student_record[1]['first_name'] = "John"
student_record[1]['last_name'] = "Wick"
student_record[1]['dept'] = "Engineering"
student_record[1]['major'] = "CSE"
student_record[1]['year'] = 2022
student_record[2]['first_name'] = "Albert"
student_record[2]['last_name'] = "Sons"
student_record[2]['dept'] = "Engineering"
student_record[2]['major'] = "ECE"
student_record[2]['year'] = 2023
for i in range(1, 3):
print(student_record[i])