Chapter 5: Sets and dictionaries

Grouping data with dict

face Josiah Wang

Another good use case for dict is as a flexible C++ struct. For example, you can have a dictionary representing a single student, with the student’s properties represented as keys:

Representing an instance of a person using a dictionary

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

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

student = {
            "name": "Josiah", 
            "id": "00-02-11", 
            "degree": "MSc 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"])
???

You can also use a tuple 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])
???