Skip to main content

defaultdict with deepcopy support

Project description


This is a package for a defaultdict that deep copies its default value.

This can be used to implement a simple counter object, similar to the example code this is based on.

counter = DefaultDict()

for item in ['spam', 'egg', 'spam', 'spam', 'bacon', 'spam']:
    counter[item] += 1

print("Menu contents:")
for item in counter:
    print("  {}x {}".format(counter[item], item))


Menu contents:
  1x bacon
  1x egg
  4x spam

Unlike collections.defaultdict, the default value is an object - not a factory. This allows for easier creation of nested data structures. For example, the following is valid and encouraged:

# shapes_by_color[color][shape] = count
shapes_by_color = DefaultDict(
        {'total': 0},

with open('test/shapes.log', 'r') as fp:
    for line in fp:
        color, shape = line.split()
        shapes_by_color[color][shape] += 1
        shapes_by_color[color]['total'] += 1

for color, shapes in shapes_by_color.items():
    for shape, count in shapes.items():
        if shape == 'total':
        print("  {}x {}".format(count, shape))
    print("  Total: {}".format(count))


  2x triangle
  1x circle
  Total: 3
  1x octagon
  2x rhombus
  Total: 3
  1x triangle
  1x square
  Total: 2

Note that the default value is a reference, and is affected by external changes. This only affects new uses of the default value, not previous uses.

spam = DefaultDict(default=['Hello'])




['Hello', 'world']
DictWithDefault(init={'sausage': ['Hello', 'world'], 'eggs': ['Hello']}, default=['Hello', 'world'])

Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for defaultdict-NickNackGus, version 1.0.2
Filename, size File type Python version Upload date Hashes
Filename, size defaultdict_NickNackGus-1.0.2-py3-none-any.whl (3.9 kB) File type Wheel Python version py3 Upload date Hashes View
Filename, size defaultdict-NickNackGus-1.0.2.tar.gz (2.6 kB) File type Source Python version None Upload date Hashes View

Supported by

AWS AWS Cloud computing Datadog Datadog Monitoring Facebook / Instagram Facebook / Instagram PSF Sponsor Fastly Fastly CDN Google Google Object Storage and Download Analytics Huawei Huawei PSF Sponsor Microsoft Microsoft PSF Sponsor NVIDIA NVIDIA PSF Sponsor Pingdom Pingdom Monitoring Salesforce Salesforce PSF Sponsor Sentry Sentry Error logging StatusPage StatusPage Status page