liveBook · Manning

Dict.get

As explained in The Quick Python Book, Fourth Edition

The dictionary get method retrieves the value associated with a key and can return a specified fallback when the key is absent.

dict.get retrieves the value for a dictionary key without raising KeyError when the key is absent. Pass a fallback as the second argument, or receive None by default. section 3.2.5 section 7.2

Use the method according to the lookup you need:

  • dictionary.get(key, fallback) returns the stored value when key exists and fallback otherwise. section 7.2
  • dictionary.get(key) returns None when key is absent. section 7.2
  • Use in when you need to test membership; use setdefault when a missing key should also be inserted. section 7.2

Counting words

sample_string = "To be or not to be" occurrences = {} for word in sample_string.split(): occurrences[word] = occurrences.get(word, 0) + 1 Here, a new word starts at 0, while an existing word's count is incremented. section 7.3

print(english_to_french.get('blue', 'No translation'))
 
bleu
 
print(english_to_french.get('chartreuse', 'No translation'))        #1
 
No translation
#1 Chartreuse not found, “No translation” is returned.

A translation dictionary demonstrates successful lookup and a readable fallback for an unknown word. section 7.2

element = matrix.get((rownum, colnum), 0)

A tuple-indexed sparse matrix uses get to return zero for elements that are not explicitly stored. section 7.5

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Defines optional fallbacks, contrasts membership and setdefault, and applies the method in counting and sparse-matrix examples.
Examples
Uses translation lookup, word-frequency counting, and tuple-indexed sparse-matrix access.
What it assumes
Uses dictionaries, keys, values, and basic loops without introducing programming fundamentals.
What you can do after
Apply it via Python to retrieve values, supply defaults, count words, and read absent sparse-matrix entries as zero.
How it connects
Connects dictionaries with KeyError, membership testing, setdefault, defaultdict, Counter, and sparse matrices.

Also explained in

Compare how 5 books explain dict.get →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.