Defaultdict extension for dictionaries with multiple levels of nesting
Project description
Overview
collections.defaultdict allows dictionaries to be created with default values.
For example, a dictionary of sets:
from collections import defaultdict dd = defaultdict(set) dd["1st group"].add(3) dd["2nd group"].add(5) dd["2nd group"].add(8) dd["1st group"].add(4) dd["2nd group"].add(5) print dict(dd)gives:
{'1st group': set([3, 4]), '2nd group': set([8, 5])})This module extends this to dictionaries with more than one level of nesting:
from nested_dict import * nd = nested_dict() nd["a"]["b"]["c"] = 311 nd["d"]["e"] = 311Each nested level is create magically when accessed, a process known as “auto-vivification” in perl.
How to use nested_dict:
“Auto-vivifying” nested dict
nd= nested_dict() nd["mouse"]["chr1"]["+"] = 311 nd["mouse"]["chromosomes"]="completed" nd["mouse"]["chr2"] = "2nd longest" nd["mouse"]["chr3"] = "3rd longest" for k, v in nd.iteritems_flat(): print "%-30s=-%20s" % (k,v)Gives:
('mouse', 'chr3') =- 3rd longest ('mouse', 'chromosomes') =- completed ('mouse', 'chr2') =- 2nd longest ('mouse', 'chr1', '+') =- 311
Specifying the autovivified object
If you wish the nested dictionary to hold a collection rather than a scalar, you have to write:
nd["mouse"]["chr2"] = list() nd["mouse"]["chr2"].append(12)or:
nd["mouse"]["chr2"] = set() nd["mouse"]["chr2"].add(84)Which doesn’t seem very “auto” at all!
Instead, specify the collection in the constructor of nested_dict:
# two levels of nesting nd2 = nested_dict(2, list) nd2["mouse"]["chr2"].append(12) # three levels of nesting nd3 = nested_dict(3, set) nd3["mouse"]["chr2"]["categorised"].add(3) # counts nd4 = nested_dict(2, int) nd4["mouse"]["chr2"]+=4 nd4["human"]["chr1"]+=3 nd4["human"]["chr3"]+=4
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 Distributions
nested_dict-1.0.0.zip
(9.0 kB
view hashes)
nested_dict-1.0.0.tar.gz
(5.0 kB
view hashes)