Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Python Dictionary

  1. Home
  2. Python Dictionary
  3. dict.get() / dict.setdefault()

dict.get() / dict.setdefault()

Since: Python 2(2000)

Methods for safely retrieving keys from a dictionary and setting default values when a key does not exist. They are essential for preventing KeyError.

Syntax

dict.get(key, default=None)

# If the key does not exist, sets the default value and returns it. If the key already exists, returns the existing value.
dict.setdefault(key, default=None)

Method List

MethodDescription
dict.get(key, default=None)Returns the value for the key if it exists, otherwise returns default. The dictionary is not modified.
dict.setdefault(key, default=None)Returns the value for the key if it exists. If the key does not exist, adds key: default to the dictionary and returns default.

Sample Code

dict_get_setdefault.py
person = {"name": "Kiryu Kazuma", "age": 37, "city": "Kamurocho"}

# Retrieve an existing key.
print(person.get("name")) # Kiryu Kazuma
print(person.get("age")) # 37

# Retrieving a missing key with get() returns None.
print(person.get("email")) # None

# Specify a default value.
print(person.get("email", "Not registered")) # Not registered
print(person.get("phone", "000-0000")) # 000-0000

# The difference between get() and [].
# person["email"] # Raises KeyError.
# person.get("email") # No error — returns None.

# A practical example: branch logic based on a config value.
config = {"debug": True, "timeout": 30}
log_level = config.get("log_level", "INFO") # Default is "INFO"
print(f"Log level: {log_level}") # Log level: INFO

# Use setdefault() to set a value only when the key is absent.
user = {"name": "Majima Goro"}
user.setdefault("role", "guest") # "role" is missing, so it is added.
print(user) # {'name': 'Majima Goro', 'role': 'guest'}

user.setdefault("role", "admin") # "role" already exists, so nothing changes.
print(user) # {'name': 'Majima Goro', 'role': 'guest'}  (not changed to admin)

# A common pattern: using setdefault() to group items into lists.
# Convenient for building a "dict of lists" structure.
members_by_org = {}
items = [
    ("Tojo Clan", "Kiryu Kazuma"), ("Omi Alliance", "Saejima Taiga"), ("Tojo Clan", "Nishikiyama Akira"),
    ("Freelance", "Majima Goro"), ("Omi Alliance", "Dojima Daigo")
]
for org, name in items:
    members_by_org.setdefault(org, []).append(name)

print(members_by_org)
# {'Tojo Clan': ['Kiryu Kazuma', 'Nishikiyama Akira'], 'Omi Alliance': ['Saejima Taiga', 'Dojima Daigo'], 'Freelance': ['Majima Goro']}

# The same result can be achieved with collections.defaultdict.
from collections import defaultdict
members_by_org2 = defaultdict(list)
for org, name in items:
    members_by_org2[org].append(name)

print(dict(members_by_org2)) # Same result.

# Count name occurrences using get().
names = ["Kiryu Kazuma", "Majima Goro", "Kiryu Kazuma", "Nishikiyama Akira", "Majima Goro", "Kiryu Kazuma"]
count = {}
for name in names:
    count[name] = count.get(name, 0) + 1
print(count) # {'Kiryu Kazuma': 3, 'Majima Goro': 2, 'Nishikiyama Akira': 1}

Running the code produces the following output:

python3 dict_get_setdefault.py
Kiryu Kazuma
37
None
Not registered
000-0000
Log level: INFO
{'name': 'Majima Goro', 'role': 'guest'}
{'name': 'Majima Goro', 'role': 'guest'}
{'Tojo Clan': ['Kiryu Kazuma', 'Nishikiyama Akira'], 'Omi Alliance': ['Saejima Taiga', 'Dojima Daigo'], 'Freelance': ['Majima Goro']}
{'Tojo Clan': ['Kiryu Kazuma', 'Nishikiyama Akira'], 'Omi Alliance': ['Saejima Taiga', 'Dojima Daigo'], 'Freelance': ['Majima Goro']}
{'Kiryu Kazuma': 3, 'Majima Goro': 2, 'Nishikiyama Akira': 1}

Common Mistakes

Common Mistake 1: The Default Value in get() Is Always Evaluated

The default value in get(key, default) is always evaluated, even when the key exists. If generating the default value is costly, use a conditional expression or setdefault() instead.

members = {'Kiryu Kazuma': 'Dojima Family', 'Majima Goro': 'Majima Family'}

# This always creates [] even when 'Akiyama Shun' is absent (cost is low here, but worth noting)
result = members.get('Akiyama Shun', [])

# setdefault: sets and adds the default only when the key is absent
members.setdefault('Akiyama Shun', 'Sky Finance')
print(members['Akiyama Shun']) # 'Sky Finance' (key was added)

# existing keys are not affected
members.setdefault('Kiryu Kazuma', 'Another Org') # already exists, no change
print(members['Kiryu Kazuma']) # 'Dojima Family' (unchanged)

Common Mistake 2: Confusing KeyError with [] Access

Accessing a dictionary with [] using a key that does not exist raises a KeyError. Use get() to retrieve values safely.

members = {'Kiryu Kazuma': 'Dojima Family', 'Majima Goro': 'Majima Family'}

# accessing a missing key with [] raises KeyError
try:
    org = members['Nishikiyama Akira'] # KeyError: 'Nishikiyama Akira'
except KeyError:
    print('Key not found')

The same logic can also be written as:

org = members.get('Nishikiyama Akira', 'Unknown')
print(org) # 'Unknown' (no error)

Notes

When accessing a dictionary value, using [] with a key that does not exist raises a KeyError. Whenever you are unsure whether a key exists, always use get() or check with the in operator before accessing it.

The key difference between setdefault() and get() is whether the dictionary is modified. setdefault() adds a default value to the dictionary when the key is absent. This behavior is commonly used in the pattern of setting an empty list on the first access and appending data to it thereafter.

For counting or aggregating words, collections.Counter from the standard library is more concise. For updating and removing dictionary entries, see dict.update() / dict.pop().

If you find any errors or copyright issues, please .