Python dictionary get() - How to get the (default) value by a given key

The Python dictionary method get() returns the value of a given key.

d = {
    'book': 28,
    'pen': 145,
}

a = d.get('book')
b = d.get('car')

print(a)  # 28
print(b)  # None

book is a key and 28 is its value. So get('book') returns 28. Though d doesn't have car key, get('car') returns None instead of raising an exception.

Let's compare the above example to just referencing with brackets. Referencing raises the KeyError exception if the dictionary doesn't have a key.

d = {
    'book': 28,
    'pen': 145,
}

a = d['book']
print(a)  # 28

b = d['note']
print(b)  # KeyError: 'note'

If you want to get precise values of a dictionary and don't need default values, using square brackets may be safe.

Get the default value

get() can take two arguments; key and default value (option).

d = {
    'book': 97,
    'pen': 145,
}

a = d.get('book', 2)
b = d.get('car', 3)

print(a)  # 97
print(b)  # 3

d doesn't have car but get() returns 3 because the second optional argument is 3. This option is None by default. d has book so a is 97, not 2. The default value is ignored if the key exists. So the summary is that this method

  • returns the value and ignores the default value if the key exists
  • returns the default value if the key doesn't exist
  • and the default value is None by default.

Note that get() resembles setdefault and both are Python dictionary methods. setdefault() returns the value if the key exists and adds the pair if the key doesn't exist. Both methods are confusing but it's important to know the difference of get() and setdefault().

Empty dictionary

d = {}

a = d.get('book')
b = d.get('note', 5)

print(a)  # None
print(b)  # 5

It's a tiny example but interesting to see get() return the default value though the original dictionary is empty.

No argument

d = {'apple': 3, 'lemon': 4}

a = d.get()

# TypeError: get expected at least 1 argument, got 0

If there is no argument, Python raises the TypeError exception.

Example 1

d = {
    'book': 28,
    'pen': 145,
}

a = d.get(None)
b = d.get(None, 5)

print(a)  # None
print(b)  # 5

It's a strange example but Python doesn't raise the exception. The dictionary doesn't have None key so get() returns the default value.

Python Dictionary

Python Tutorial