Is there an elegant way to create a layered dictionary in python?

I would like to create a multi-level dictionary, for example:

A = { 'a': { 'A': { '1': {}, '2': {}, }, 'B': { '1': {}, '2': {}, }, }, 'b': { 'A': { '1': {}, '2': {}, }, 'B': { '1': {}, '2': {}, }, }, } 

My question is whether there was a function with which I can build the aforementioned diction:

 D = function(['a', 'b'], ['A', 'B'], ['1', '2'], {}) 
+4
source share
4 answers

It uses a copy function that allows you to specify a different leaf node. Otherwise, all sheets point to the same dictionary.

 from copy import copy def multidict(*args): if len(args) == 1: return copy(args[0]) out = {} for x in args[0]: out[x] = multidict(*args[1:]) return out print multidict(['a', 'b'], ['A', 'B'], ['1', '2'], {}) 
+5
source
 def multi(*args): if len(args) > 1: return {arg:multi(*args[1:]) for arg in args[0]} else: return args[0] multi(['a', 'b'], ['A', 'B'], ['1', '2'], {}) 

returns

 {'a': {'A': {'1': {}, '2': {}}, 'B': {'1': {}, '2': {}}}, 'b': {'A': {'1': {}, '2': {}}, 'B': {'1': {}, '2': {}}}} 

EDIT . In my solution, the last argument {} will be copied to each output sheet as a reference to the same dictionary. If this is a problem (replacing it with an immutable object like float, integer or string, is another thing), use the idea of copy.copy @matt.

+5
source

Easy to write with recusion

 def multi_level_dict(*args): x = dict() if args: for k in args[0]: x[k] = multi_level_dict(*args[1:]) return x 

your business will be

 multi_level_dict(["a", "b"], ["A", "B"], ["1", "2"]) 

or even

 multi_level_dict("ab", "AB", "12") 
+2
source

A dict understanding is a cool approach for this, but only with a fixed nesting depth:

 {x:{y:{z:{} for z in ['1', '2']} for y in 'AB'} for x in 'ab'} 
0
source

All Articles