0Pricing
Python Academy · Lesson

defaultdict

Auto-initialize dictionary values.

defaultdict is a free Python Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

The missing-key problem

With a normal dict, accessing a key that does not exist raises KeyError. This is annoying when you want to build up values incrementally.

d = {}
try:
    d['x'].append(1)
except KeyError as e:
    print('KeyError:', e)

Enter defaultdict

defaultdict from collections takes a factory function that produces a default value for any missing key. Import it with from collections import defaultdict.

from collections import defaultdict
d = defaultdict(int)
print(d['missing'])
print(dict(d))

Counting with int

With defaultdict(int), missing keys default to 0, so you can increment without checking first.

from collections import defaultdict
counts = defaultdict(int)
for ch in 'banana':
    counts[ch] += 1
print(dict(counts))

Grouping with list

defaultdict(list) creates an empty list for new keys, perfect for grouping items into buckets.

from collections import defaultdict
groups = defaultdict(list)
words = ['apple', 'ant', 'bee', 'bear']
for w in words:
    groups[w[0]].append(w)
print(dict(groups))

Collecting with set

Use defaultdict(set) when you want unique values per key. Duplicates are dropped automatically.

from collections import defaultdict
seen = defaultdict(set)
pairs = [('a', 1), ('a', 1), ('a', 2), ('b', 3)]
for k, v in pairs:
    seen[k].add(v)
print(dict(seen))

The factory must be callable

The argument is a callable that takes no arguments and returns the default. int, list, set, and dict all work because calling them returns an empty value.

from collections import defaultdict
print(int())
print(list())
print(set())

Custom default with lambda

You can supply any zero-argument callable, such as a lambda, to return a custom default value.

from collections import defaultdict
scores = defaultdict(lambda: 100)
print(scores['new_player'])
scores['alice'] -= 10
print(dict(scores))

Nested defaultdicts

A factory can itself create a defaultdict, letting you build nested structures without manual setup.

from collections import defaultdict
table = defaultdict(lambda: defaultdict(int))
table['fruit']['apples'] += 3
table['fruit']['pears'] += 2
print(table['fruit']['apples'])
print(table['fruit']['pears'])

Access creates the key

Be aware: simply reading a missing key inserts it with the default value. After access the key exists in the dictionary.

from collections import defaultdict
d = defaultdict(int)
_ = d['ghost']
print('ghost' in d)
print(dict(d))

Checking without inserting

To check a key without creating it, use the .get() method or the in operator, which never trigger the factory.

from collections import defaultdict
d = defaultdict(int)
print(d.get('safe', 'default'))
print('safe' in d)
print(dict(d))

Converting back to dict

Wrap a defaultdict in dict() when you want a plain dictionary, for example before returning it from a function or printing cleanly.

from collections import defaultdict
dd = defaultdict(list)
dd['a'].append(1)
plain = dict(dd)
print(type(plain))
print(plain)

Quick Check

What does the argument passed to defaultdict represent?

Recap: defaultdict

Key points:

  • defaultdict(factory) auto-creates values for missing keys.
  • int gives 0 (counting), list gives [] (grouping), set gives empty set (unique grouping).
  • The factory is any zero-argument callable, including a lambda.
  • Reading a missing key inserts it; use .get() or in to peek safely.
from collections import defaultdict
g = defaultdict(list)
for w in ['cat', 'cow', 'dog']:
    g[w[0]].append(w)
print(dict(g))

Frequently asked questions

Is the “defaultdict” lesson free?

Yes — the full text of “defaultdict” is free to read here on the web, and the Python Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO.

What will I learn in “defaultdict”?

Auto-initialize dictionary values. You practise Python Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Python Academy?

No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “defaultdict” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Python Academy lesson?

Yes. Every Python Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Counter
  2. defaultdict
  3. deque
  4. namedtuple and OrderedDict
← Back to Python Academy