This is an archived version of the course. Please see the latest version of the course.

Grouping data with dict and tuple

Another good use case for dict is as a flexible object structure (like a Java class with just instance variables/attributes). For example, you can have a dictionary representing a single student, with the student’s properties represented as keys:

>>> student = {"name": "Josiah", 
...             "id": "00-02-11", 
...             "degree": "MSc Computing"
...            }
>>> print(student["name"])
>>> print(student["id"])
>>> print(student["degree"])

You can technically have any object as values. It is very frequent to have nested structures.

>>> student = {"name": "Josiah", 
...            "id": "00-02-11", 
...            "degree": "MEng Computing",
...            "courses": [
...                {
...                    "title": "Introduction to Machine Learning", 
...                    "code": "60012"
...                },
...                { 
...                    "title": "Computer Vision",
...                    "code": "60006"
...                }
...             ]
...            }
>>> print(student["courses"])
>>> print(student["courses"][0])
>>> print(student["courses"][0]["title"])
>>> print(student["courses"][0]["code"])

Tuples can also be used to group data.

>>> course1 = ("60012", "Introduction to Machine Learning")
>>> course2 = ("60006", "Computer Vision")
>>>
>>> student_record = ("Josiah", "00-02-11", "MSc Computing", [course1, course2])
>>>
>>> print(student_record[1])
>>> print(student_record[3])
>>> print(student_record[3][0])