How can I write a recursive python function that splits a dictionary into an array of dictionaries? -
i looking write recursive function:
arguments: d, dictionary result: list of dictionaries def expand_dictionary(d): return []
the function recursively goes through dictionary , flattens nested objects using _, in addition expands out nested lists array, , includes parent label.
think of creating relational model document.
here example input , output:
original_object = { "id" : 1, "name" : { "first" : "alice", "last" : "sample" }, "cities" : [ { "id" : 55, "name" : "new york" }, { "id" : 60, "name" : "chicago" } ], "teachers" : [ { "id" : 2 "name" : "bob", "classes" : [ { "id" : 13, "name" : "math" }, { "id" : 16, "name" : "spanish" } ] } ] } expected_output = [ { "id" : 1, "name_first" : "alice", "name_last" : "sample" }, { "_parent_object" : "cities", "id" : 55, "name" : "new york" }, { "_parent_object" : "cities", "id" : 60, "name" : "chicago" }, { "parent_object" :"teachers", "id" : 2, "name" : "bob" }, { "parent_object" :"teachers_classes", "id" : 13, "name" : "math" }, { "parent_object" :"teachers_classes", "id" : 16, "name" : "spanish" } ]
the code being used flattening is:
def flatten_dictionary(d): def expand(key, value): if isinstance(value, dict): return [ (key + '_' + k, v) k, v in flatten_dictionary(value).items() ] else: #if value null or empty array don't include if value none or value == [] or value == '': return [] return [ (key, value) ] items = [ item k, v in d.items() item in expand(k, v) ] return dict(items)
that do
def expand_dictionary(d,name=none,l=none): obj = {} if l == none: l = [obj] else: l.append(obj) prefix = (name+'_'if name else '') if prefix: obj['_parent_object'] = name i, v in d.iteritems(): if isinstance(v, list): map(lambda x:expand_dictionary(x,prefix+i,l),v) elif isinstance(v, dict): obj.update(flatten_dictionary({i: v})) else: obj[i] = v return l
Comments
Post a Comment