Rewrite with dictionary instead of tree