defaultdict with deepcopy support
Project description
DefaultDict
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))
Output:
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(
default=DefaultDict(
{'total': 0},
default=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():
print("{}:".format(color))
for shape, count in shapes.items():
if shape == 'total':
continue
print(" {}x {}".format(count, shape))
print(" Total: {}".format(count))
Output:
green:
2x triangle
1x circle
Total: 3
red:
1x octagon
2x rhombus
Total: 3
blue:
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'])
print(spam['eggs'])
spam.default.append('world')
print(spam['sausage'])
print(spam)
Output:
['Hello']
['Hello', 'world']
DictWithDefault(init={'sausage': ['Hello', 'world'], 'eggs': ['Hello']}, default=['Hello', 'world'])
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Close
Hashes for defaultdict-NickNackGus-1.0.0.tar.gz
Algorithm | Hash digest | |
---|---|---|
SHA256 | 5ff3314feeec6adda49d67988b2eaca4b29038b5e9e21ef96d9e60645706fa46 |
|
MD5 | 4ed73340c26b236597d5d3cbde461e98 |
|
BLAKE2b-256 | 4b8dd2689d06e60c5510fd601c8cecc85de865c35e771dc9a574d13ebc7b914f |
Close
Hashes for defaultdict_NickNackGus-1.0.0-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 446eca67c5702a16e7b07b0722fd7d26651a967c7766c7283f892c1375e73da2 |
|
MD5 | 0a097d85e3a830a26e97bf891d755b6d |
|
BLAKE2b-256 | cc7f661195efb10d355b151c7e38287794b9beceeb861380ad96c0824636cfeb |