Many right implementations could be using lists or tuples, but none would be optimised for performance.
Python provides a data structure Dictionary for such cases. A dictionary in simple words is a data structure which stores the key-value pairs.
For example: if you want to store information about a student
student = { 'Name': 'Aaliyan', 'Class': 'AI', 'Program': 'PIAIC', 'Age': 42 }
Please note that keys must be between single or double quotation if they are string type, every pair is separated from other pairs by a comma ( , ), and every pair of key value is separated by a colon ( : ).
Accessing information from Dictionary
student = { 'Name': 'Zaid', 'Class': 'AI', 'Program': 'PIAIC', 'Age': 42 }
print(student['Name'])
If you try to access any key not present in the dictionary will raise an exception of type Key error. Also, beware of the fact that the Keys are case sensitive, hence the following statement will throw an exception of type Key error.
print(student['name']) # Exception
because the name key does not exist in the student dictionary.
Dictionary adding keys
student = { 'Name': 'Zaid', 'Class': 'AI', 'Program': 'PIAIC', 'Age': 42 }
In the dictionary student, we don’t have the FatherName key what if now I want to assign a value to this key in the dictionary?
student['FatherName'] = 'Bakar'
When we are assigning a value in a key which does not exist, Python creates the key and assigns the value in the key. If a key is already present the value is overwritten.
Dictionary removing items
student = { 'Name': 'Zaid', 'Class': 'AI', 'Program': 'PIAIC', 'Age': 42 }
There are cases when you must delete a key-value pair from the dictionary.
del student['Program']
print(student)
Dictionary iterating items
Python provides 3 methods over dictionary objects to iterate over dictionary values, keys and key-value pair
student = { 'Name': 'Zaid', 'Class': 'AI', 'Program': 'PIAIC', 'Age': 42}
for value in student.values():
print(value)
for key in student.keys():
print(key)
Dictionary; what you can store
Any data structure we have studied so far we can store as value in the dictionary.
- The dictionary can contain a list
- Tuple
- Any type of primitive or user-defined (in future lectures we will study them as classes)
- Dictionary, a dictionary can store another dictionary as its value
- Or a combination of these
List of Dictionaries
Creating a list of dictionaries
To mimic a database we can create a list of dictionaries, where the list will be an in-memory database and each dictionary object will represent a unique record. For example:
students[]
students.append({ 'Name': 'Ali', 'Class': 'AI', 'Campus': 'PIAIC Campus 1'})
students.append({ 'Name': 'Jinnah', 'Class': 'AI', 'Campus': 'PIAIC Campus 2'})
Accessing info from a list of dictionaries
We are already familiar with the list of elements accessed by their index. Hence, to access any dictionary object you need its index to access it.
students = []
students.append({ 'Name': 'Ali', 'Class': 'AI', 'Campus': 'PIAIC Campus 1'})
students.append({ 'Name': 'Jinah', 'Class': 'AI', 'Campus': 'PIAIC Campus 2'})
for student in students:
print(student)
a dictionary that holds a list
As we have studied to access the value of a dictionary we provide a key name inside square brackets, in this case, the value is a list so an extra pair of square brackets is used to access the list element.
employee = { 'Name': 'Shams', 'ChildrenNames': ['Humairah', 'Abdul Rehman']}
print(employee['ChildrenNames'][0])
print(employee['ChildrenNames'][1])
a dictionary that holds a dictionary
In this snippet, we created a dictionary inside the dictionary, and the child’s name is used as a key. In the first print statement we can observe that the first pair of square brackets with employee returns a dictionary to access the elements of that dictionary we provide another pair with a key.
employee = { 'Name': 'Shams', 'Children': {'Humairah': {'Age': 10, 'Class': '6th Standard' }, 'Abdul Rahman': {'Age': 8, 'Class': '4th Standard' }}}
print(employee['Children']['Humairah'])
print(employee['Children']['Abdul Rahman']['Age'])