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
