Meaning
Retrieves the value for a given key from a dictionary, returning a specified default if the key is absent.
Primary Function
Perform a safe dictionary lookup with a fallback default value.
Communicative Purpose
Provide a default value when a dictionary key might be missing, avoiding KeyError exceptions.
Pattern
dict.get(key, default)
Core Structure
object.method(key, default)
Função primária
Perform a safe dictionary lookup with a fallback default value.
Propósito comunicativo
Provide a default value when a dictionary key might be missing, avoiding KeyError exceptions.
Situações de gatilho
When accessing dictionary entries where the key may not be present and a default value is desired instead of raising an exception.
Contextos
Used in data processing, configuration lookup, caching, or any scenario where dictionary lookups may fail.
Padrão
dict.get(key, default)
Estrutura central
object.method(key, default)
Slots de substituição
my_dict: any mapping object; key: hashable key; default: any value to return if key is missing
Colocados típicos
- dict
- key
- default
- None
- 0
- empty string
Substituições comuns
- dict[key] if key in dict else default
- dict.setdefault(key
- default)
Erros comuns
Using dict[key] without checking leads to KeyError; forgetting to provide a default results in None being returned unintentionally
Similar / contraste
dict.setdefault(key, default) also sets the key if missing; dict.pop(key, default) removes and returns the key
Interferências
Coming from Java: Map.get returns null for missing keys, leading to expecting None instead of providing a default; Coming from JavaScript: obj[key] returns undefined for missing keys, so developers may forget to supply a default and unintentionally receive None.
Família do chunk
- dictionary access patterns
Nuance
The default is returned only when the key is absent; if the key exists with a falsy value (e.g., 0, ''), that value is returned, not the default.
Efeito pragmático
Provides a concise, safe way to handle missing keys, improving code robustness and readability.
Dica de memória
Think 'get or default'.
Nota
Note that dict.get does not insert the key into the dictionary; use dict.setdefault if insertion of the default value is desired.
Upgrade path
Using dict.setdefault to both retrieve and set default, or using collections.defaultdict for automatic defaults.
Log in to save chunks.