dict.get
d.get(key, default=None)Return the value for key if it is present, otherwise return default.
| Parameter | Description |
|---|---|
key | The key to look up. |
default | Value returned when the key is absent. Defaults to None. |
Returns: The stored value, or default if the key is missing. This method does not raise KeyError.
- d[key] raises KeyError when the key is missing. get() does not.
- If the stored value can also be None (or whatever you used as default), check membership first.
config = {"port": 80, "host": None}
print(config.get("port"))
print(config.get("debug", False))
print("host" in config, config.get("host"))
print("debug" in config, config.get("debug"))Expected output
80
False
True None
False NoneRelated: Compare dictionary keys and values, Official dict methods