dict. get()
Returns the value for a key, or a default value when the key is not in the dictionary.
- Returns
- The value assigned to the key, or
default. - Changes the original
- No
Example
#student = {"name": "Emma", "points": 1240}
print(student.get("name"))
print(student.get("level"))
print(student.get("level", 1))
print(student)Definition and usage
#The get(key) method reads a value from a dictionary much like square brackets, but it does not raise an error when the key is missing. Instead of KeyError, it returns None or the value given as the second argument.
That makes it a good fit for data where some fields are optional, for example user settings or API responses. Writing settings.get("theme", "dark") sets the fallback value right away.
The method only reads and does not add the missing key to the dictionary. If you also want to store the default value, use setdefault(). Keep in mind too that get() cannot tell a missing key apart from a key whose value is None. The in operator is the tool for that.
Syntax
#dict.get(key, default=None)Parameters
#key
a dictionary key
The key whose value you want to read.default
optional, default None
The value returned when the key is not in the dictionary.
More examples
#settings = {"theme": "dark"}
try:
print(settings["lang"])
except KeyError as error:
print("KeyError:", error)
print(settings.get("lang", "en"))answers = ["B", "A", "B", "C", "B"]
counts = {}
for answer in answers:
counts[answer] = counts.get(answer, 0) + 1
print(counts)Good practices
#- Use square brackets for keys that must exist, because their absence is a bug worth noticing. Leave
get()for optional fields. - The default value is evaluated before the method is called, even when the key exists. Do not put expensive computations inside
get(); use a condition withininstead. collections.Counteris more convenient for counting occurrences, andcollections.defaultdictfor grouping.
Related entries
#- dict.setdefault()Returns the value of a key, and first stores a default value in the dictionary when the key is missing.
- dict.pop()Removes a key from a dictionary and returns its value, optionally with a fallback value.
- dict.keys()Returns a view of the dictionary's keys that always reflects its current contents.
- dict()Creates a dictionary from key-value pairs or keyword arguments.
Spotted a mistake or missing an example? Write to us.