Chapter 7: Dictionaries
Introduces dictionaries as Python’s useful associative arrays or maps, implemented using hash tables.
After this chapter you will be able to
- Dictionary identity and usefulness. Explain that a dictionary is Python’s associative array or map, implemented using a hash table, and that dictionaries are useful even in simple programs.
- Dictionary keys and mappings. Explain how a dictionary maps keys to values and why keys such as names make it useful for tasks that do not fit list indexing.
- Dictionary creation and insertion. Describe how to create an empty dictionary, assign a value under a key, and retrieve it, including what happens when the key is new.
- Dictionary contents and views. Describe what keys, values, and items return, and explain how their results behave when the dictionary changes.
- Safe missing-key lookup. Explain how in and get handle a key that may be absent from a dictionary.
- Defaults stored in dictionaries. Distinguish setdefault from get when a key is missing, and state the related behavior described for defaultdict.
- Dictionary removal and update. Describe how del removes an entry and how update incorporates another dictionary’s entries, including shared keys.
- Dictionary word counting pattern. Explain how to count words by using each word as a dictionary key and using get() to retrieve and increment its count.
- Dictionary key eligibility. Explain that a dictionary key must be both immutable and hashable, and distinguish eligible numbers and strings from mutable lists and dictionaries.
- Tuple keys and contents. Explain how a tuple can serve as a listlike composite key, and why a tuple containing a mutable object does not qualify.
- Sparse matrix memory savings. Explain why storing only nonzero matrix elements can save memory when a large matrix contains mostly zeros.
- Dictionary based matrix access. Describe how a dictionary represents a sparse matrix using row-and-column tuples as keys, and how `get` can return zero for a position that has no stored entry.
- Dictionary caching of function results. Explain how the rewritten sole function uses a dictionary to reuse results for repeated combinations of its three arguments, and why that can save time.
- Dictionary efficiency tradeoff. Justify choosing a dictionary over a list when it solves a problem more easily and cleanly, and state when to consider alternatives.
- Dictionary word count representation. Describe how to count the words in the prepared file: start with an empty dictionary, use each word as a key, and store its number of occurrences as the value.
- Sortable word count pairs. Explain how `items()` helps produce the requested report: it provides word keys and count values as tuples that can be sorted to find the five most common and five least common words.
- Dictionary word-counting prompt. Explain how to prompt an AI chatbot for this word-counting task: specify the input file, require a dictionary rather than the Counter class, and request counts for the five most and five least common words. Explain why the prompt need not spell out how to read the file.
What it builds on
- Dictionaries (chapter 3) · Previously introduces dictionaries among Python’s built-in data types.
- List indices (chapter 5) · List access by integer index.
- Modifying lists (chapter 5) · The limits of assignment to list positions.
- Nested lists and deep copies (chapter 5) · The introduction to shallow and deep copies.
- Tuple basics (chapter 5) · The distinction between lists and tuples.
- Lists are like arrays (chapter 5) · The use of lists as array-like data structures.
- Preprocessing text (chapter 6) · The earlier lab produced the file of separated words used here.
- Sorting lists (chapter 5) · Sorting lists provides background for ordering the tuples.
Section by section
Introduction
Introduces dictionaries as Python’s useful associative arrays or maps, implemented using hash tables.
- Dictionary identity and usefulness: Explain that a dictionary is Python’s associative array or map, implemented using a hash table, and that dictionaries are useful even in simple programs.
Why it matters: This gives you a starting point for recognizing when the chapter is discussing dictionaries.
Key terms: dictionaries, associative arrays, maps, hash tables
7.1 What is a dictionary?
This section introduces dictionaries as key-to-value mappings, contrasts them with lists, and shows how to create, populate, and use them.
- Dictionary keys and mappings: Explain how a dictionary maps keys to values and why keys such as names make it useful for tasks that do not fit list indexing.
Why it matters: Choosing a meaningful key lets you look up information by what identifies it, rather than by a list position. - Dictionary creation and insertion: Describe how to create an empty dictionary, assign a value under a key, and retrieve it, including what happens when the key is new.
Why it matters: You can build a dictionary by assigning values to new keys without first creating numbered positions. - Dictionary item ordering: Distinguish a list's positional ordering from a dictionary's insertion order.
Why it matters: Insertion order should not be confused with the numbered positions used to access list values.
Key terms: dictionary, key, mapping, list index, empty dictionary, curly braces, assignment, list indices, dictionary keys, order they were added
7.2 Other dictionary operations
This section explains how to inspect, look up, copy, and modify dictionaries beyond basic key assignment and access.
- Dictionary contents and views: Describe what keys, values, and items return, and explain how their results behave when the dictionary changes.
Why it matters: These methods let you work with a dictionary’s contents without treating its views as fixed lists. - Dictionary key ordering: Distinguish the key ordering described for Python 3.5 and earlier from the behavior starting in Python 3.6.
Why it matters: Creation order and sorted order are different expectations when reading dictionary keys. - Safe missing-key lookup: Explain how in and get handle a key that may be absent from a dictionary.
Why it matters: These operations let you handle absent keys without making an erroneous direct access. - Defaults stored in dictionaries: Distinguish setdefault from get when a key is missing, and state the related behavior described for defaultdict.
Why it matters: The distinction determines whether handling a missing key also changes the dictionary. - Shallow and deep copies: Explain what dictionary copy makes and when the section suggests using copy.deepcopy instead.
Why it matters: The kind of values in a dictionary affects which copying method is appropriate. - Dictionary removal and update: Describe how del removes an entry and how update incorporates another dictionary’s entries, including shared keys.
Why it matters: These operations change a dictionary’s entries, including resolving keys shared with another dictionary.
Key terms: keys, values, items, dictionary view objects, creation order, in, get, None, setdefault, defaultdict
7.3 Word counting
Shows how a dictionary can count occurrences of words in a file and notes why this pattern is useful.
- Dictionary word counting pattern: Explain how to count words by using each word as a dictionary key and using get() to retrieve and increment its count.
Why it matters: This is a compact pattern for tallying how often items occur. - Counting pattern practicality: Describe why dictionary-based word counting is practical and name the standard-library class that provides this pattern.
Why it matters: The section connects a simple counting technique with its performance and a ready-made standard-library option.
Key terms: dictionary key, get() method, count, dictionary operations, Counter, collections module
7.4 What can be used as a key?
This section explains which objects can be dictionary keys and why tuples work as composite keys only when their contents are hashable.
- Dictionary key eligibility: Explain that a dictionary key must be both immutable and hashable, and distinguish eligible numbers and strings from mutable lists and dictionaries.
Why it matters: This rule lets you decide whether a proposed value can identify a dictionary entry. - Tuple keys and contents: Explain how a tuple can serve as a listlike composite key, and why a tuple containing a mutable object does not qualify.
Why it matters: It explains how to use several values together as a key without assuming that every tuple is valid.
Key terms: dictionary key, immutable, hashable, mutable, tuple, hash value, __hash__, mutable objects
7.5 Sparse matrices
This section explains how a dictionary can store a large matrix efficiently when most of its elements are zero.
- Sparse matrix memory savings: Explain why storing only nonzero matrix elements can save memory when a large matrix contains mostly zeros.
Why it matters: It explains why a dictionary may be preferable to a list of lists for a mostly zero matrix. - Dictionary based matrix access: Describe how a dictionary represents a sparse matrix using row-and-column tuples as keys, and how `get` can return zero for a position that has no stored entry.
Why it matters: It shows how to retrieve a value from a sparse representation without storing its zero entries.
Key terms: matrix, sparse matrices, nonzero elements, dictionaries, tuple indices, row and column, get method
7.6 Dictionaries as caches
This section explains how a dictionary can cache results of an expensive function so repeated calls with the same arguments do not recalculate them.
- Dictionary caching of function results: Explain how the rewritten sole function uses a dictionary to reuse results for repeated combinations of its three arguments, and why that can save time.
Why it matters: Caching can save substantial time when an expensive function is repeatedly called with the same arguments.
Key terms: cache, dictionary, tuples as keys, argument combinations
7.7 Efficiency of dictionaries
This section explains why efficiency concerns usually should not deter readers from choosing a dictionary when it makes a solution cleaner.
- Dictionary efficiency tradeoff: Justify choosing a dictionary over a list when it solves a problem more easily and cleanly, and state when to consider alternatives.
Why it matters: You can choose the data structure that expresses your solution clearly without assuming dictionaries are too slow.
Key terms: dictionaries, lists (arrays), efficient, unacceptable slowdown
7.8 Word counting
This lab outlines how to count words in a previously prepared file with a dictionary and report the most and least common words.
- Dictionary word count representation: Describe how to count the words in the prepared file: start with an empty dictionary, use each word as a key, and store its number of occurrences as the value.
Why it matters: This gives each word a place to accumulate its count as the file is processed. - Sortable word count pairs: Explain how `items()` helps produce the requested report: it provides word keys and count values as tuples that can be sorted to find the five most common and five least common words.
Why it matters: Keeping each word with its count makes it possible to report both together at either end of the frequency list.
Key terms: dictionary, keys, values, word counts, items(), tuples
7.8.1 Solving the problem with AI-generated code
This subsection shows how to prompt an AI chatbot to solve the word-counting exercise with a dictionary and specified output.
- Dictionary word-counting prompt: Explain how to prompt an AI chatbot for this word-counting task: specify the input file, require a dictionary rather than the Counter class, and request counts for the five most and five least common words. Explain why the prompt need not spell out how to read the file.
Why it matters: An explicit prompt makes it more likely that the generated solution follows the exercise’s dictionary requirement.
Key terms: prompt, dictionary, Counter class, moby_01_clean.txt
7.8.2 Solutions and discussion
7.9 Summary
Where this is used later
- The for loop (chapter 8) · For loops can iterate over dictionary contents.
- Pickling objects to files (chapter 13) · Caching calculation results in a dictionary keyed by their arguments.
- Useful functions (chapter 9) · Earlier word-counting work supplies code to revisit.
Concepts explained in this chapter
- MapA map is an associative data structure that stores key-value pairs and supports retrieving values by key.
- items methodThe dictionary items method returns the dictionary's key-value pairs as iterable tuple-like items.
- list()The list function is a Python built-in constructor that creates a new list from an iterable or sequence of elements.
- setdefault methodThe setdefault method is a dictionary method that returns a key's value and inserts the key with a specified default value when the key is absent.
- keyA dictionary key is a hashable identifier used to access an associated value in a Python dictionary.
- dict.getThe dictionary get method retrieves the value associated with a key and can return a specified fallback when the key is absent.
- copyCopying is the creation of a separate representation of an existing value, object, or data, preserving some or all of its contents or state.
- del statementA del statement is Python syntax for deleting names, items, or slices from objects that support deletion.
- tupleA tuple is an ordered, immutable collection that can contain multiple values, including values of different types.
- reversingThe reverse method is a Python list operation that reverses the order of elements in the list in place.
- immutable collectionImmutability is the property of an object or data structure that prevents its contents from being changed after creation.
- cachingA cache is stored data containing previously computed results so that later requests can reuse them without repeating the computation.
- functionA function is a callable program unit that performs an operation, may accept inputs, and can produce a result or side effect.
- word countA word count is the number of words identified in a text according to a specified word-segmentation rule.
- code generationCode generation is the automated production of source code from prompts, specifications, templates, or other inputs.
- promptA prompt is an instruction or input supplied to an AI system to elicit a particular response or generated output.
- deep copyA deep copy is a recursively independent copy of a container and the modifiable objects nested within it.
- inheritanceInheritance is an object-oriented mechanism by which a class derives behavior and structure from another class, forming a hierarchy of related classes.
- integerAn integer is a whole-number value with no fractional component and, in Python, arbitrary magnitude subject to available memory.
- stringA string is an immutable sequence of characters represented as a Python value.
- global variableA global variable is a name bound at module or program level that can be accessed and modified by functions that explicitly declare it global.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
