Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

collections.defaultdict is a dict subclass that creates and stores a value when you access a missing key with square brackets. Pass a zero-argument callable such as list, int or set to define that value. It is especially useful for grouping and accumulation—but subscription can mutate the dictionary, so use .get() when a read must not create a key.

What defaultdict does

Import defaultdict from Python’s standard-library collections module. It behaves like a dictionary, with one additional rule: when subscription looks up a missing key, the dictionary can call a factory, store the returned value under that key, and return it. The official reference describes its default_factory and __missing__ behavior.

from collections import defaultdict

scores = defaultdict(list)
scores["Alice"].append(95)
scores["Alice"].append(88)

print(scores)
# defaultdict(<class 'list'>, {'Alice': [95, 88]})

The first subscription to scores["Alice"] calls list(), stores a new empty list for that key, and returns it. The append then changes that stored list. This makes the default policy part of the mapping itself, rather than repeating an initialization check wherever values are added.

Construct a defaultdict

The first positional argument is default_factory. It must be callable or None; any remaining arguments are used to initialize the mapping as they would be for dict.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
from collections import defaultdict

by_name = defaultdict(list)
counts = defaultdict(int)
unique_values = defaultdict(set)
nested = defaultdict(dict)
labels = defaultdict(lambda: "unknown")
no_factory = defaultdict()

If the factory is omitted or is None, a missing subscription raises KeyError. A callable is passed, not its result:

defaultdict(list)    # Correct: list is called for each missing key
defaultdict(list())  # TypeError: an empty list is not a callable factory
defaultdict([])      # TypeError: the factory must be callable or None

When a key is missing, the factory is called with no arguments. Consequently, a factory that requires arguments cannot be used directly; a lambda can supply fixed arguments, but it still cannot receive the missing key.

When a missing key is created

Creation happens through subscription, d[key], when that key is absent and default_factory is not None. Conceptually, the mapping calls the factory, stores its result, and returns the result. If the factory raises an exception, that exception propagates.

Operation Calls the factory for a missing key? Creates a key?
d[key] Yes, if a factory is set Yes, if the factory returns successfully
d.get(key) No No
key in d No No
d.keys() or d.items() No No

For example, d.get("missing") returns None by default, even on a defaultdict(list). You can supply a one-off fallback with d.get("missing", []); it is returned but not inserted. This distinction also means a subscription used only to inspect a key can change what later code sees.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
d = defaultdict(list)

print("x" in d)  # False
print(d["x"])    # []: creates the key
print("x" in d)  # True

If the key already exists, its value is returned as-is. The factory does not replace a stored None, zero, empty list, or other falsey value. Use key in d when you need to distinguish absence from a stored falsey value.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Common uses

Group values into lists

With a plain dictionary, grouping usually requires checking whether each group exists before appending. The official documentation includes this grouping pattern.

pairs = [
    ("fruit", "apple"),
    ("vegetable", "carrot"),
    ("fruit", "banana"),
]

grouped = defaultdict(list)
for category, item in pairs:
    grouped[category].append(item)

print(dict(grouped))
# {'fruit': ['apple', 'banana'], 'vegetable': ['carrot']}

Here, each first subscription creates a separate list for its category.

Accumulate counts with integers

int() returns zero, so an increment works on a new key without an explicit initialization step.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
counts = defaultdict(int)
for character in "mississippi":
    counts[character] += 1

print(dict(counts))
# {'m': 1, 'i': 4, 's': 4, 'p': 2}

For a straightforward frequency table, collections.Counter communicates the intent more directly; it is a dictionary subclass designed for counting hashable objects, as described in the standard-library documentation.

from collections import Counter

counts = Counter("mississippi")

Collect distinct values with sets

A set factory is useful when each group should contain unique values. Repeated additions of the same value have no effect.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
users_by_role = defaultdict(set)
users_by_role["admin"].add("alice")
users_by_role["admin"].add("bob")
users_by_role["admin"].add("alice")

print(dict(users_by_role))
# {'admin': {'alice', 'bob'}}

Build nested mappings

Factories can be nested to support multiple levels of accumulation:

data = defaultdict(lambda: defaultdict(int))
data["sales"]["January"] += 10
data["sales"]["February"] += 15

print(data["sales"]["January"])  # 10

For arbitrarily deep trees, use a recursive factory:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
def tree():
    return defaultdict(tree)

config = tree()
config["database"]["connection"]["timeout"] = 30

Each missing level touched by subscription is created. Even config["unused"]["branch"] creates both keys, so use explicit checks or non-mutating lookups if merely exploring a tree should not change it.

Return a constant fallback

A lambda can return a constant for every missing key:

labels = defaultdict(lambda: "unknown")
print(labels["missing"])  # unknown

Because the factory takes no arguments, it cannot produce a default based on the missing key. For that, use explicit lookup logic or a custom mapping with a key-aware __missing__ method. Also ensure a custom factory creates mutable values independently rather than returning the same object repeatedly:

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
shared = []
bad = defaultdict(lambda: shared)
bad["a"].append(1)
print(bad["b"])  # [1]: both keys point to the same list

good = defaultdict(list)
# Each missing key receives a fresh list

Choose between defaultdict and alternatives

Need Good starting point Behavior to consider
Group values into lists defaultdict(list) Subscription creates and stores a list for each new group.
Count hashable items Counter Purpose-built for frequency counting.
Read with a fallback without mutation dict.get() The fallback is returned but not inserted.
Initialize and mutate while keeping a regular dict dict.setdefault() Concise for simple cases; its default expression is evaluated before the call.
Missing keys should be errors dict Ordinary subscription raises KeyError for an absent key.
Default depends on the missing key Explicit logic or a custom mapping A defaultdict factory receives no key argument.

Use get() for read-only fallback lookups

Use mapping.get(key, fallback) when the fallback is needed for one lookup and a miss should not alter the mapping. This is usually the clearer choice in read-oriented code or validation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use setdefault() with a regular dictionary when appropriate

setdefault returns the existing value or inserts and returns the given default. It can express grouping without changing the mapping type:

groups = {}
for key, value in pairs:
    groups.setdefault(key, []).append(value)

Be aware that Python evaluates the default expression before calling setdefault, even when the key already exists. For example, mapping.setdefault(key, expensive_default()) calls expensive_default() each time that line runs.

Keep a plain dictionary when implicit insertion is undesirable

A regular dict is often preferable for public interfaces, conditional initialization, or mappings where a missing key signals an error. If you need a custom missing-key policy based on the key, a dictionary subclass can define __missing__; unlike a defaultdict factory, that method receives the key.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Typing, conversion, and newer dictionary operations

Type annotations

For Python 3.9 and later, the built-in generic spelling can annotate a constructed defaultdict:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
from collections import defaultdict

groups: defaultdict[str, list[int]] = defaultdict(list)

This annotation describes the concrete container and its key and value types; it does not construct the object. Older typing conventions used typing.DefaultDict, documented by PEP 484. For function parameters, prefer an abstract interface such as Mapping for read-only access or MutableMapping when mutation is required, if the function does not depend on defaultdict-specific behavior.

Convert when a plain dictionary is expected

The representation of a defaultdict includes its factory, for example defaultdict(<class 'list'>, {}). Use dict(d) to produce a plain dictionary for a consumer that should not see the specialized container. For nested structures, convert recursively if plain dictionaries are required at every level:

def to_dict(value):
    if isinstance(value, defaultdict):
        return {key: to_dict(item) for key, item in value.items()}
    if isinstance(value, dict):
        return {key: to_dict(item) for key, item in value.items()}
    if isinstance(value, list):
        return [to_dict(item) for item in value]
    return value

Serialization behavior varies by serializer and configuration; converting to built-in containers makes the intended structure explicit but does not determine every serializer’s output rules.

Merge dictionaries with | and |=

defaultdict supports the dictionary merge operators introduced in Python 3.9 by PEP 584:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
left = defaultdict(list, {"a": [1]})
right = {"b": [2]}

merged = left | right
left |= right

These are dictionary merges, not recursive accumulation: if both mappings contain a key, the value from the right-hand mapping replaces the left-hand value. Lists are not automatically concatenated.

Mapping patterns do not create missing keys

A structural pattern match checks keys already present; attempting a mapping pattern does not invoke defaultdict.__missing__ to manufacture a key. This behavior is described in PEP 622.

config = defaultdict(str)

match config:
    case {"host": host}:
        print(host)
    case _:
        print("No existing host key")

Common mistakes and safer fixes

  • Passing a value instead of a factory: use defaultdict(list), not defaultdict([]) or defaultdict(list()).
  • Assuming a factory gets the key: it is called with no arguments. Use explicit logic or a custom mapping for key-dependent defaults.
  • Reading through subscription accidentally grows the mapping: replace an inspection such as if cache[user_id] with if cache.get(user_id) when no insertion is intended.
  • Confusing falsey and absent: an existing value of 0, None, or [] does not invoke the factory. Check membership when presence matters.
  • Returning one shared mutable value: use a factory such as list that creates a fresh object for each key.
  • Creating nested paths during inspection: recursive default factories create each missing level accessed; use membership checks or non-mutating lookup for exploratory reads.

Check behavior with focused tests

These assertions verify that a non-mutating lookup leaves a missing key absent and that mutable defaults are independent:

from collections import defaultdict

d = defaultdict(list)
assert "missing" not in d
value = d.get("missing")
assert "missing" not in d

d["a"].append(1)
assert d["b"] == []
assert d["a"] is not d["b"]

When the same mapping is shared across threads, do not assume a compound expression such as d[key].append(value) is an application-level transaction. A Python core-development discussion describes version-sensitive concurrency details around __missing__; it is not a final language specification. Protect shared mutable mappings with an appropriate lock, or use a design that avoids shared mutation. If correctness depends on concurrent initialization, verify the behavior for the exact Python implementation and version you deploy.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.