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
On this page

Example

#
Python
student = {"name": "Emma", "points": 1240}

print(student.get("name"))
print(student.get("level"))
print(student.get("level", 1))
print(student)
Resultsaved result, you can check it
Emma
None
1
{'name': 'Emma', 'points': 1240}

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

#
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

#
Square brackets vs. get()
Python
settings = {"theme": "dark"}

try:
    print(settings["lang"])
except KeyError as error:
    print("KeyError:", error)

print(settings.get("lang", "en"))
Resultsaved result, you can check it
KeyError: 'lang'
en
Counting answers
Python
answers = ["B", "A", "B", "C", "B"]
counts = {}

for answer in answers:
    counts[answer] = counts.get(answer, 0) + 1

print(counts)
Resultsaved result, you can check it
{'B': 3, 'A': 1, 'C': 1}

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 with in instead.
  • collections.Counter is more convenient for counting occurrences, and collections.defaultdict for grouping.

Related entries

#

Spotted a mistake or missing an example? Write to us.