@@ -202,18 +202,45 @@ def write(self, format: str = MF6) -> None:
202202 for child in self .children .values (): # type: ignore
203203 child .write (format = format )
204204
205- def to_dict (self , blocks : bool = False ) -> dict [str , Any ]:
206- """Convert the component to a dictionary representation."""
205+ def to_dict (self , blocks : bool = False , strict : bool = False ) -> dict [str , Any ]:
206+ """
207+ Convert the component to a dictionary representation.
208+
209+ Parameters
210+ ----------
211+ blocks : bool, optional
212+ If True, return a nested dict keyed by block name
213+ with values as dicts of fields. Default is False.
214+ strict : bool, optional
215+ If True, include only fields in the DFN specification.
216+
217+ Returns
218+ -------
219+ dict[str, Any]
220+ Dictionary containing component data, either
221+ in terms of fields (flat) or blocks (nested).
222+ """
207223 data = xattree_asdict (self )
208- data .pop ("filename" )
209- data .pop ("workspace" , None ) # might be a Context
210- data .pop ("nodes" , None ) # TODO: find a better way to omit
224+ spec = self .dfn .fields
225+
226+ if strict :
227+ data .pop ("filename" )
228+ data .pop ("workspace" , None ) # might be a Context
229+
211230 if blocks :
212231 blocks_ = {} # type: ignore
213- for field_name , field_value in data .items ():
214- block_name = self .dfn .fields [field_name ].block
232+ for field_name in spec .keys ():
233+ field_value = data [field_name ]
234+ block_name = spec [field_name ].block
235+ if strict and block_name is None :
236+ continue
215237 if block_name not in blocks_ :
216238 blocks_ [block_name ] = {}
217239 blocks_ [block_name ][field_name ] = field_value
218240 return blocks_
219- return data
241+ else :
242+ return {
243+ field_name : data [field_name ]
244+ for field_name in spec .keys ()
245+ if spec [field_name ].block or not strict
246+ }
0 commit comments