liveBook · Manning

Setdefault method

As explained in The Quick Python Book, Fourth Edition

The 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.

setdefault safely retrieves a dictionary value while ensuring that a missing key receives a specified default. It returns the existing value when the key is present; otherwise, it inserts the key with the default and returns that value. section 7.2

Use the method with two arguments:

  • dictionary.setdefault(key, default) returns the key's value. section 7.2
  • An existing key keeps its current value; a missing key is added with the supplied default. section 7.2
  • Unlike get, setdefault changes the dictionary when the key is absent. The get method only returns a fallback value. section 7.2

Adding a missing translation

english_to_french = {'red': 'rouge', 'blue': 'bleu', 'green': 'vert'} print(english_to_french.setdefault('chartreuse', 'No translation')) # No translation print(english_to_french['chartreuse']) # No translation The missing chartreuse key is added while its default value is returned. Calling the method for an existing key returns the stored value without replacing it. section 7.2

Counting words

word_count = {} with open("moby_01_clean.txt", "r") as infile: for word in infile: word = word.strip() word_count.setdefault(word, 0) word_count[word] += 1 The first occurrence creates a zero entry; the following statement increments it. Later, items() supplies word-frequency pairs that can be sorted to find common and uncommon words. section 7.8.2

print(english_to_french.setdefault('chartreuse', 'No translation')) #1
 
No translation
#1 Chartreuse not found and is added as key, and “No translation” is returned and added as its value.

Inspect the compact chartreuse example showing the returned default and the newly inserted dictionary entry. section 7.2

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains return and insertion behavior, contrasts get, and demonstrates counting without descending into implementation internals.
Examples
Demonstrates a missing translation and initializes word counts before sorting word-frequency pairs.
What it assumes
Assumes familiarity with Python dictionaries, keys, values, indexing, and loops while teaching default insertion through examples.
What you can do after
Apply it via Python dictionaries to initialize missing values and update accumulated counts.
How it connects
Connects setdefault with dictionaries, get, items, word-frequency counting, and defaultdict.

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.