#!/usr/bin/env python # -*- coding: utf-8 -*- from vector_dict.VectorDict import convert_tree a = convert_tree( dict( a = 1, e = dict( b = dict( c= 1, d = True ) ), x= [ 1 , 2], z= 1.0 )) ### Traditionnal representation of a rooted tree made ### when implemented with dict of dict a.tprint() # OUT: { # OUT: a = 1, # OUT: x = [1, 2], # OUT: z = 1.0, # OUT: e = { # OUT: b = { # OUT: c = 1, # OUT: d = True, # OUT: }, # OUT: }, # OUT: } ### Flattening a tree as a vector ### which makes tree homeomorph to a vector a.pprint() # OUT: a = 1 # OUT: x = [1, 2] # OUT: z = 1.0 # OUT: e->b->c = 1 # OUT: e->b->d = True
"names": { "en": "" } }, "country": { "iso_code": "" }, "location": { "time_zone": "" }, "postal": { "code": "" } }''') big_tree = convert_tree(big_dict) tmpl_tree = convert_tree(tmpl_dict) big_tree.intersection(tmpl_tree, ignore_value_difference=True).tprint() """ { u'city' : { u'names' : { u'en' : 'McAllen', }, }, u'postal' : { u'code' : '78504', }, u'location' : {
) if cmd_folder not in sys.path: sys.path.insert(0, cmd_folder) from vector_dict.Clause import Clause, is_leaf, is_container from vector_dict.Operation import identity, mul, cast from vector_dict.VectorDict import convert_tree from vector_dict.SparseMatrix import SparseMatrix,Coordinates from collections import namedtuple, defaultdict a = convert_tree( { 'a' : { 'b' : 1 , 'c' : 2 } , 'b' : 0 } ) def title(string): print print "*" * 80 print string print "*" * 80 title( "initial dictionary" ) a.tprint() m = SparseMatrix( ## take source['a'][b'] and * -2 and put it in dst['mul']['neg2'] ( tuple( [ 'a', 'b' ] ), tuple([ 'mul', 'neg2' ] ), mul(-2) ), ## guess :) ( tuple([ 'a', 'c' ]), tuple([ 'mul', 'misplaced' ]), cast(float) ), ( tuple([ 'b' ]) , tuple([ 'a' ]) , lambda x : -4 ),
def findme( v, a_tree): if not is_leaf(v): return v.match_tree(a_tree) positive = lambda v : v > 0 def pretty_present(list): print "Result " for el in list: print "path %r " % el[0] print "has value %s" % (hasattr(el[1], 'tformat') and el[1].tformat() or el[1] ) print w = convert_tree( dict( a = dict( c= 1), e = dict( d= 3.0) , b = dict( c = 1 , d = 4 ) )) w.tprint() pretty_present( w.find( lambda p, v : has_all( 'c', 'd' )(v) ) ) pretty_present( w.find( lambda p, v : findme(v, dict( d= has_type(int), c=has_type(int) ) ) ) ) pretty_present( w.find( lambda p, v : has_tree({ 'a' : { 'c' : positive } })(v)) ) pretty_present( w.find( lambda p, v : (