nested_dictDefaultdict extension for dictionaries with multiple levels of nesting | |
Download |
nested_dict Ranking & Summary
Advertisement
- License:
- Other/Proprietary Li...
- Price:
- FREE
- Publisher Name:
- Leo Goodstadt
- Publisher web site:
- http://code.google.com/u/bunbun68/
nested_dict Tags
nested_dict Description
Defaultdict extension for dictionaries with multiple levels of nesting nested_dict is a Python module that extends collections.defaultdict to allow dictionaries with multiple levels of nesting to be created on the fly: from nested_dict import * nd = nested_dict() nd = 311 nd = 311 Each nested level is create magically when accessed, a process known as "auto-vivification" in perl.nested dictionaries of sets / lists and other collections nested_dict also extends collections.defaultdict to allow dictionaries of lists, sets or other collections with a specified level of nesting level.1) The old fashioned way using ugly syntax d = dict() d.setdefault(""1st group", []).append(3) d.setdefault(""2nd group", []).append(5) d.setdefault(""2nd group", []).append(8) d.setdefault(""1st group", []).append(4) d.setdefault(""2nd group", []).append(5)2) default_dict adds lists automatically when required from collections import defaultdict dd = defaultdict(list) dd.append(3) dd.append(5) dd.append(8) dd.append(4) dd.append(5)3) nested_dict adds lists automatically when required for nested dictionaries from nested_dict import nested_dict # specify two levels of nesting nd = nested_dict(2, list) nd.append(3) nd.append(5) nd.append(8) nd.append(4) nd.append(5) print nd gives: {'1st group': {'subset a': }, '2nd group': {'subset b': , 'subset a': }}More examples:"Auto-vivifying" nested dict nd= nested_dict() nd = 311 nd="completed" nd = "2nd longest" nd = "3rd longest" for k, v in nd.iteritems_flat(): print "%-30s=- s" % (k,v) Gives ('mouse', 'chr3') =- 3rd longest ('mouse', 'chromosomes') =- completed ('mouse', 'chr2') =- 2nd longest ('mouse', 'chr1', '+') =- 311Specifying the autovivified object If you wish the nested dictionary to hold a collection rather than a scalar, you have to write: nd = list() nd.append(12) or: nd = set() nd.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.append(12) # three levels of nesting nd3 = nested_dict(3, set) nd3.add(3) # counts nd4 = nested_dict(2, int) nd4+=4 nd4+=3 nd4+=4 Requirements: · Python
nested_dict Related Software