3 Using built-in data containers

 

This chapter covers

  • When to choose lists over tuples and vice versa
  • Advanced sorting of lists that consist of complex data types
  • Using named tuples as a data container model
  • Accessing dictionary’s data
  • Hashability and its implications for dictionaries and sets
  • Set operations and their applications for non-set data

As a general-purpose programming language, Python provides a range of built-in data types for different purposes, including collection types, which serve as data containers to hold integers, strings, instances of custom classes, and all other kinds of objects. In every project, we deal with multiple objects at the same time, and these scenarios often require data containers to handle these objects. Every modern language has data containers as their core data models, highlighting the importance of data containers as building blocks for any programming project. As you'll see in chapter 14 when we build our task management app, we'll use data containers for a variety of jobs, such as using a list to hold custom instances of the Task class (chapter 8). In this chapter, we’ll discuss the key aspects of using built-in data containers, including lists, tuples, dictionaries, and sets.

Terminology

Data containers are objects that contain other objects, such as lists, which can contain multiple strings. By contrast, strings and integers are not containers, as they don't contain other objects.

3.1 How do I choose between lists and tuples?

3.1.1 Tuples support immutability while lists support mutability

3.1.2 Using tuples for heterogeneity and using lists for homogeneity

3.1.3 Discussion

3.1.4 Challenge

3.2 How do I sort lists of complicated data using custom functions?

3.2.1 Sorting lists using the default order

3.2.2 Using a built-in function as the sorting key

3.2.3 Using custom functions for more complicated sorting needs

3.2.4 Discussion

3.2.5 Challenge

3.3 How do I build a lightweight data model using named tuples?

3.3.1 Understanding alternative data models

3.3.2 Creating named tuples to hold data

3.3.3 Discussion

3.3.4 Challenge

3.4 How do I access dictionary keys, values, and items?

3.4.1 Using dynamic view objects (keys, values, and items) directly

3.4.2 Being cautious with the KeyError exception

sitemap