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




