Above we focused on lists and dictionaries as somewhat separated data structures. However, they can be combined. We can have lists that contain dictionaries, dictionaries that contain lists and so on (we can even have dictionaries containing dictionaries or lists containing lists). This is a useful aspect to recall when planning what kinds of data structures are used.
For example, a list of dictionaries can store many of the detailed data entries easily. Code Example 5.13 shows how to store information about a group of people, such as names, ages and zip codes. We can do this by creating a people list. Each item on the list is a dictionary with meaningful keys, such as first name, last name, age and zip code. As the example shows, these details can be accessed by going through (iterating) a list and then taking each item and working on it as a list. This approach can help ensure that more complex data are accessed always in the right manner. Some data storage formats, like JSON, often present the data like this.
Alternatively, a dictionary can use a list as a value to which cases are stored. Code Example 5.15 demonstrates a case where this might be required to simplify the problem. We are collecting different cases to analyse these as a group further. However, doing a lot of different forms of analysis, we could first collect each case into its own lists. In cases of gender, this would lead to at least three lists: men, women and other. However, we do not want to manually create three different lists and control what data go to which lists using several if-statements (see Code Examples 5.14). To avoid creating different list variables for each case, we should use a dictionary instead. Thus, we have a dictionary where keys are group names, and values are lists that contain the data.