Skip to content

NestedDict

Bases: MutableMapping

Nested dictionary data structure.

Handle nested dictionaries with an interface similar to standard dictionaries.

Parameters:

Name Type Description Default
dictionary dict

Input nested dictionary.

None
copy bool

Set to True to copy the input dictionary.

False
See Also

NestedDict.from_product: Initialize from cartesian product.

NestedDict.from_tuples: Initialize from list of tuples.

Examples:

Initialize from a nested dictionary.

>>> d = {"a": {"a": 0, "b": 1}, "b": 2}
>>> nd = NestedDict(d)
>>> nd
NestedDict({'a': {'a': 0, 'b': 1}, 'b': 2})

Get an item.

>>> nd["a"]
{'a': 0, 'b': 1}
>>> nd[("a", "b")]
1

Set an item.

>>> nd[("c", "a")] = 3
>>> nd
NestedDict({'a': {'a': 0, 'b': 1}, 'b': 2, 'c': {'a': 3}})

Delete an item.

>>> del nd["c"]
>>> nd
NestedDict({'a': {'a': 0, 'b': 1}, 'b': 2})

Iterate over keys.

>>> [key for key in nd]
[('a', 'a'), ('a', 'b'), ('b',)]
>>> [key for key in nd.keys()]
[('a', 'a'), ('a', 'b'), ('b',)]

Iterate over values.

>>> [value for value in nd.values()]
[0, 1, 2]

Iterate over items.

>>> [item for item in nd.items()]
[(('a', 'a'), 0), (('a', 'b'), 1), (('b',), 2)]
Source code in ndicts\nested_dict.py
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
class NestedDict(MutableMapping):
    """
    Nested dictionary data structure.

    Handle nested dictionaries with an interface
    similar to standard dictionaries.

    Args:
        dictionary (dict): Input nested dictionary.
        copy (bool): Set to True to copy the input dictionary.

    See Also:
        NestedDict.from_product: Initialize from cartesian product.

        NestedDict.from_tuples: Initialize from list of tuples.

    Examples:
        Initialize from a nested dictionary.

        >>> d = {"a": {"a": 0, "b": 1}, "b": 2}
        >>> nd = NestedDict(d)
        >>> nd
        NestedDict({'a': {'a': 0, 'b': 1}, 'b': 2})

        Get an item.

        >>> nd["a"]
        {'a': 0, 'b': 1}
        >>> nd[("a", "b")]
        1

        Set an item.

        >>> nd[("c", "a")] = 3
        >>> nd
        NestedDict({'a': {'a': 0, 'b': 1}, 'b': 2, 'c': {'a': 3}})

        Delete an item.

        >>> del nd["c"]
        >>> nd
        NestedDict({'a': {'a': 0, 'b': 1}, 'b': 2})

        Iterate over keys.

        >>> [key for key in nd]
        [('a', 'a'), ('a', 'b'), ('b',)]
        >>> [key for key in nd.keys()]
        [('a', 'a'), ('a', 'b'), ('b',)]

        Iterate over values.

        >>> [value for value in nd.values()]
        [0, 1, 2]

        Iterate over items.

        >>> [item for item in nd.items()]
        [(('a', 'a'), 0), (('a', 'b'), 1), (('b',), 2)]
    """

    @classmethod
    def from_tuples(cls, tuples: List[Iterable], values: Union[Any, Iterable] = None) -> T:
        """
        Initialize a NestedDict from a list of iterables.

        Args:
            tuples:
                Tuples corresponding to the keys of the NestedDict.
            values:
                If values is an iterable but not a string,
                its values will become to those of the NestedDict.
                If a non-iterable or string is passed,
                it will be assigned to each value of the NestedDict.

        Returns:
            NestedDict

        Raises:
            UnequalIterablesError: If the keys and values have different length.

        Examples:
            >>> tuples = [("a", "aa"), ("b",)]
            >>> NestedDict.from_tuples(tuples)
            NestedDict({'a': {'aa': None}, 'b': None})

            Initialize with a single value.

            >>> NestedDict.from_tuples(tuples, values=0)
            NestedDict({'a': {'aa': 0}, 'b': 0})

            Initialize with different values.

            >>> NestedDict.from_tuples(tuples, values=[0, 1])
            NestedDict({'a': {'aa': 0}, 'b': 1})

            Passing values with the wrong size will throw an exception.

            >>> NestedDict.from_tuples(tuples, values=range(99))
            Traceback (most recent call last):
            ...
            more_itertools.recipes.UnequalIterablesError: Iterables have different lengths...
        """
        nd = cls()
        if isinstance(values, Iterable) and not isinstance(values, str):
            for key, value in zip_equal(tuples, values):
                nd[key] = value
        else:
            for key in tuples:
                nd[key] = values
        return nd

    @classmethod
    def from_product(cls, iterables: List[Iterable], values: Union[Any, Iterable] = None) -> T:
        """
        Initialize a NestedDict by cartesian product.

        Args:
            iterables:
                Input iterables.
            values:
                If values is an iterable but not a string,
                it will be assigned to the values of the NestedDict.
                If a non-iterable or string is passed,
                it will be assigned to each value of the NestedDict.

        Returns:
            NestedDict

        Raises:
            UnequalIterablesError: If the keys and values have different length.

        Examples:
            >>> iterables = [("A", "B"), ("a", "b")]
            >>> NestedDict.from_product(iterables)
            NestedDict({'A': {'a': None, 'b': None}, 'B': {'a': None, 'b': None}})

            Initialize with a single value.

            >>> NestedDict.from_product(iterables, values=0)
            NestedDict({'A': {'a': 0, 'b': 0}, 'B': {'a': 0, 'b': 0}})

            Initialize with different values.

            >>> NestedDict.from_product(iterables, values=[0, 1, 2, 3])
            NestedDict({'A': {'a': 0, 'b': 1}, 'B': {'a': 2, 'b': 3}})

            Passing values with the wrong size will throw an exception.

            >>> NestedDict.from_product(iterables, values=range(99))
            Traceback (most recent call last):
            ...
            more_itertools.recipes.UnequalIterablesError: Iterables have different lengths
        """
        keys = product(*iterables)
        return cls.from_tuples(keys, values)

    def __init__(self, dictionary: dict = None, copy: bool = False) -> None:
        """
        Initialize a NestedDict from a dictionary.

        See class docstring.
        """
        if dictionary is None:
            dictionary = {}
        self._ndict = deepcopy(dictionary) if copy else dictionary

    def __getitem__(self, key: Union[Any, Tuple]) -> Any:
        """
        Get item associated to the key.

        Args:
            key:
                Either comma-separated values or tuples.

        Returns:
            Value associated to the key.

        Raises:
            KeyError: If the key does not belong to the NestedDict.

        Examples:
            >>> d = {"a": {"a": 0, "b": 1}}
            >>> nd = NestedDict(d)

            Get the first level.

            >>> nd["a"]
            {'a': 0, 'b': 1}

            Get a deeper value.

            >>> nd["a", "a"]
            0

            Tuples can be passed too.
            >>> nd[("a", "b")]
            1

            An exception is thrown if they key does not exist.

            >>> nd["z"]
            Traceback (most recent call last):
            ...
            KeyError: ('z',)
        """
        if not isinstance(key, tuple):
            key = (key,)
        item = self._ndict

        for k in key:
            try:
                item = item[k]
            except KeyError:
                raise KeyError(key)
            except TypeError:
                raise KeyError(key)
        return item

    def __setitem__(self, key: Union[Any, Tuple], value: Any) -> None:
        """
        Set the key to the given value.

        If the key does not exist it is created.

        Args:
            key: Key to be set.
            value: New value for the key.

        Examples:
            Set an existing key.

            >>> nd = NestedDict({"a": {"aa": 0}})
            >>> nd["a", "aa"] = 1
            >>> nd
            NestedDict({'a': {'aa': 1}})

            Set a new key.
            >>> nd["a", "ab"] = 2
            >>> nd
            NestedDict({'a': {'aa': 1, 'ab': 2}})
        """
        if not isinstance(key, tuple):
            key = (key,)
        item = self._ndict
        for k in key[:-1]:
            item = item.setdefault(k, {})
        item[key[-1]] = value

    def __delitem__(self, key: Union[Any, Tuple]) -> None:
        """
        Delete item corresponding to the key.

        If the levels above are left empty, they are deleted.

        Args:
            key: Key as defined in NestedDict.__getitem__

        Examples:
            >>> d = {"a": {"aa": {"aaa": 0}}, "b": 1}
            >>> nd = NestedDict(d)
            >>> del nd["b"]
            >>> nd
            NestedDict({'a': {'aa': {'aaa': 0}}})

            Levels which are left empty after deleting an item are deleted too.

            >>> del nd["a", "aa", "aaa"]
            >>> nd
            NestedDict({})
        """
        if not isinstance(key, tuple):
            key = (key,)
        new_key, last_key = key[:-1], key[-1]
        del self[new_key][last_key]

        if (new_key != ()) & (self[new_key] == {}):
            self.__delitem__(new_key)

    def __iter__(self) -> Generator:
        """
        Iterate over a NestedDict.

        Yield only the keys that are associated to a leaf value.

        Note:
            NestedDict is a MutableMapping, thus it is possible
            to iterate over values, keys and items exactly as a dictionary.
            See the examples.

        Examples:
            >>> d = {"a": {"aa": 0, "ab": 1}, "b": 2}
            >>> nd = NestedDict(d)
            >>> [key for key in nd]
            [('a', 'aa'), ('a', 'ab'), ('b',)]

            Alternative to iterate over the keys.

            >>> [key for key in nd.keys()]
            [('a', 'aa'), ('a', 'ab'), ('b',)]

            Iterate over the leaf values.

            >>> [value for value in nd.values()]
            [0, 1, 2]

            Iterate over the items.
            >>> [item for item in nd.items()]
            [(('a', 'aa'), 0), (('a', 'ab'), 1), (('b',), 2)]
        """
        def wrapped(ndict, key=[]):
            """Traverse the nested dictionary recursively,
            yield the key once a leaf value is reached."""
            if not isinstance(ndict, dict):
                yield tuple(key)
            else:
                for node, branch in ndict.items():
                    key.append(node)
                    yield from wrapped(branch, key)
                    key.pop()

        return wrapped(self._ndict)

    def __len__(self) -> int:
        """
        Number of leaf values.

        Examples:
            >>> nd = NestedDict({"a": {"aa": 0, "ab": 0}, "b": 0})
            >>> len(nd)
            3
        """
        length = 0
        for _ in self:
            length += 1
        return length

    def __repr__(self) -> str:
        return f"{self.__class__.__qualname__}({self._ndict})"

    @property
    def extract(self):
        """
        Get item as a NestedDict.

        Instead of a dict or a value, a NestedDict is returned.
        The method can be used for filtering.
        An empty string "" can be used as a wildcard to match all levels.

        Examples:
             >>> nd = NestedDict.from_product(["ab", "xy"], values=0)
             >>> nd
             NestedDict({'a': {'x': 0, 'y': 0}, 'b': {'x': 0, 'y': 0}})
             >>> nd.extract["a"]
             NestedDict({'a': {'x': 0, 'y': 0}})

             Use the wildcard to extract all items with "x" on the second level.
             >>> nd.extract["", "x"]
             NestedDict({'a': {'x': 0}, 'b': {'x': 0}})
        """
        return _Extractor(self)

    def rows(self) -> Generator:
        """
        Yield the NestedDict row by row.

        A row is obtained by adding the leaf value
        to the sequence of its key.

        Notes:
            This method can be useful to export
            a NestedDict to a pandas DataFrame.

        Yields:
            A row of the NestedDict.

        Examples:
            >>> nd = NestedDict({"a": 0, "b": {"ba": 1}, "c": 2})
            >>> [row for row in nd.rows()]
            [('a', 0), ('b', 'ba', 1), ('c', 2)]
        """
        return ((*key, value) for key, value in self.items())

    def copy(self) -> T:
        """Return a deep copy."""
        return deepcopy(self)

    def to_dict(self) -> dict:
        """Return a copy as a dictionary."""
        return deepcopy(self._ndict)

extract property

Get item as a NestedDict.

Instead of a dict or a value, a NestedDict is returned. The method can be used for filtering. An empty string "" can be used as a wildcard to match all levels.

Examples:

>>> nd = NestedDict.from_product(["ab", "xy"], values=0)
>>> nd
NestedDict({'a': {'x': 0, 'y': 0}, 'b': {'x': 0, 'y': 0}})
>>> nd.extract["a"]
NestedDict({'a': {'x': 0, 'y': 0}})

Use the wildcard to extract all items with "x" on the second level.

>>> nd.extract["", "x"]
NestedDict({'a': {'x': 0}, 'b': {'x': 0}})

__delitem__(key)

Delete item corresponding to the key.

If the levels above are left empty, they are deleted.

Parameters:

Name Type Description Default
key Union[Any, Tuple]

Key as defined in NestedDict.getitem

required

Examples:

>>> d = {"a": {"aa": {"aaa": 0}}, "b": 1}
>>> nd = NestedDict(d)
>>> del nd["b"]
>>> nd
NestedDict({'a': {'aa': {'aaa': 0}}})

Levels which are left empty after deleting an item are deleted too.

>>> del nd["a", "aa", "aaa"]
>>> nd
NestedDict({})
Source code in ndicts\nested_dict.py
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
def __delitem__(self, key: Union[Any, Tuple]) -> None:
    """
    Delete item corresponding to the key.

    If the levels above are left empty, they are deleted.

    Args:
        key: Key as defined in NestedDict.__getitem__

    Examples:
        >>> d = {"a": {"aa": {"aaa": 0}}, "b": 1}
        >>> nd = NestedDict(d)
        >>> del nd["b"]
        >>> nd
        NestedDict({'a': {'aa': {'aaa': 0}}})

        Levels which are left empty after deleting an item are deleted too.

        >>> del nd["a", "aa", "aaa"]
        >>> nd
        NestedDict({})
    """
    if not isinstance(key, tuple):
        key = (key,)
    new_key, last_key = key[:-1], key[-1]
    del self[new_key][last_key]

    if (new_key != ()) & (self[new_key] == {}):
        self.__delitem__(new_key)

__getitem__(key)

Get item associated to the key.

Parameters:

Name Type Description Default
key Union[Any, Tuple]

Either comma-separated values or tuples.

required

Returns:

Type Description
Any

Value associated to the key.

Raises:

Type Description
KeyError

If the key does not belong to the NestedDict.

Examples:

>>> d = {"a": {"a": 0, "b": 1}}
>>> nd = NestedDict(d)

Get the first level.

>>> nd["a"]
{'a': 0, 'b': 1}

Get a deeper value.

>>> nd["a", "a"]
0

Tuples can be passed too.

>>> nd[("a", "b")]
1

An exception is thrown if they key does not exist.

>>> nd["z"]
Traceback (most recent call last):
...
KeyError: ('z',)
Source code in ndicts\nested_dict.py
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
def __getitem__(self, key: Union[Any, Tuple]) -> Any:
    """
    Get item associated to the key.

    Args:
        key:
            Either comma-separated values or tuples.

    Returns:
        Value associated to the key.

    Raises:
        KeyError: If the key does not belong to the NestedDict.

    Examples:
        >>> d = {"a": {"a": 0, "b": 1}}
        >>> nd = NestedDict(d)

        Get the first level.

        >>> nd["a"]
        {'a': 0, 'b': 1}

        Get a deeper value.

        >>> nd["a", "a"]
        0

        Tuples can be passed too.
        >>> nd[("a", "b")]
        1

        An exception is thrown if they key does not exist.

        >>> nd["z"]
        Traceback (most recent call last):
        ...
        KeyError: ('z',)
    """
    if not isinstance(key, tuple):
        key = (key,)
    item = self._ndict

    for k in key:
        try:
            item = item[k]
        except KeyError:
            raise KeyError(key)
        except TypeError:
            raise KeyError(key)
    return item

__init__(dictionary=None, copy=False)

Initialize a NestedDict from a dictionary.

See class docstring.

Source code in ndicts\nested_dict.py
170
171
172
173
174
175
176
177
178
def __init__(self, dictionary: dict = None, copy: bool = False) -> None:
    """
    Initialize a NestedDict from a dictionary.

    See class docstring.
    """
    if dictionary is None:
        dictionary = {}
    self._ndict = deepcopy(dictionary) if copy else dictionary

__iter__()

Iterate over a NestedDict.

Yield only the keys that are associated to a leaf value.

Note

NestedDict is a MutableMapping, thus it is possible to iterate over values, keys and items exactly as a dictionary. See the examples.

Examples:

>>> d = {"a": {"aa": 0, "ab": 1}, "b": 2}
>>> nd = NestedDict(d)
>>> [key for key in nd]
[('a', 'aa'), ('a', 'ab'), ('b',)]

Alternative to iterate over the keys.

>>> [key for key in nd.keys()]
[('a', 'aa'), ('a', 'ab'), ('b',)]

Iterate over the leaf values.

>>> [value for value in nd.values()]
[0, 1, 2]

Iterate over the items.

>>> [item for item in nd.items()]
[(('a', 'aa'), 0), (('a', 'ab'), 1), (('b',), 2)]
Source code in ndicts\nested_dict.py
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
def __iter__(self) -> Generator:
    """
    Iterate over a NestedDict.

    Yield only the keys that are associated to a leaf value.

    Note:
        NestedDict is a MutableMapping, thus it is possible
        to iterate over values, keys and items exactly as a dictionary.
        See the examples.

    Examples:
        >>> d = {"a": {"aa": 0, "ab": 1}, "b": 2}
        >>> nd = NestedDict(d)
        >>> [key for key in nd]
        [('a', 'aa'), ('a', 'ab'), ('b',)]

        Alternative to iterate over the keys.

        >>> [key for key in nd.keys()]
        [('a', 'aa'), ('a', 'ab'), ('b',)]

        Iterate over the leaf values.

        >>> [value for value in nd.values()]
        [0, 1, 2]

        Iterate over the items.
        >>> [item for item in nd.items()]
        [(('a', 'aa'), 0), (('a', 'ab'), 1), (('b',), 2)]
    """
    def wrapped(ndict, key=[]):
        """Traverse the nested dictionary recursively,
        yield the key once a leaf value is reached."""
        if not isinstance(ndict, dict):
            yield tuple(key)
        else:
            for node, branch in ndict.items():
                key.append(node)
                yield from wrapped(branch, key)
                key.pop()

    return wrapped(self._ndict)

__len__()

Number of leaf values.

Examples:

>>> nd = NestedDict({"a": {"aa": 0, "ab": 0}, "b": 0})
>>> len(nd)
3
Source code in ndicts\nested_dict.py
336
337
338
339
340
341
342
343
344
345
346
347
348
def __len__(self) -> int:
    """
    Number of leaf values.

    Examples:
        >>> nd = NestedDict({"a": {"aa": 0, "ab": 0}, "b": 0})
        >>> len(nd)
        3
    """
    length = 0
    for _ in self:
        length += 1
    return length

__setitem__(key, value)

Set the key to the given value.

If the key does not exist it is created.

Parameters:

Name Type Description Default
key Union[Any, Tuple]

Key to be set.

required
value Any

New value for the key.

required

Examples:

Set an existing key.

>>> nd = NestedDict({"a": {"aa": 0}})
>>> nd["a", "aa"] = 1
>>> nd
NestedDict({'a': {'aa': 1}})

Set a new key.

>>> nd["a", "ab"] = 2
>>> nd
NestedDict({'a': {'aa': 1, 'ab': 2}})
Source code in ndicts\nested_dict.py
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
def __setitem__(self, key: Union[Any, Tuple], value: Any) -> None:
    """
    Set the key to the given value.

    If the key does not exist it is created.

    Args:
        key: Key to be set.
        value: New value for the key.

    Examples:
        Set an existing key.

        >>> nd = NestedDict({"a": {"aa": 0}})
        >>> nd["a", "aa"] = 1
        >>> nd
        NestedDict({'a': {'aa': 1}})

        Set a new key.
        >>> nd["a", "ab"] = 2
        >>> nd
        NestedDict({'a': {'aa': 1, 'ab': 2}})
    """
    if not isinstance(key, tuple):
        key = (key,)
    item = self._ndict
    for k in key[:-1]:
        item = item.setdefault(k, {})
    item[key[-1]] = value

copy()

Return a deep copy.

Source code in ndicts\nested_dict.py
396
397
398
def copy(self) -> T:
    """Return a deep copy."""
    return deepcopy(self)

from_product(iterables, values=None) classmethod

Initialize a NestedDict by cartesian product.

Parameters:

Name Type Description Default
iterables List[Iterable]

Input iterables.

required
values Union[Any, Iterable]

If values is an iterable but not a string, it will be assigned to the values of the NestedDict. If a non-iterable or string is passed, it will be assigned to each value of the NestedDict.

None

Returns:

Type Description
T

NestedDict

Raises:

Type Description
UnequalIterablesError

If the keys and values have different length.

Examples:

>>> iterables = [("A", "B"), ("a", "b")]
>>> NestedDict.from_product(iterables)
NestedDict({'A': {'a': None, 'b': None}, 'B': {'a': None, 'b': None}})

Initialize with a single value.

>>> NestedDict.from_product(iterables, values=0)
NestedDict({'A': {'a': 0, 'b': 0}, 'B': {'a': 0, 'b': 0}})

Initialize with different values.

>>> NestedDict.from_product(iterables, values=[0, 1, 2, 3])
NestedDict({'A': {'a': 0, 'b': 1}, 'B': {'a': 2, 'b': 3}})

Passing values with the wrong size will throw an exception.

>>> NestedDict.from_product(iterables, values=range(99))
Traceback (most recent call last):
...
more_itertools.recipes.UnequalIterablesError: Iterables have different lengths
Source code in ndicts\nested_dict.py
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
@classmethod
def from_product(cls, iterables: List[Iterable], values: Union[Any, Iterable] = None) -> T:
    """
    Initialize a NestedDict by cartesian product.

    Args:
        iterables:
            Input iterables.
        values:
            If values is an iterable but not a string,
            it will be assigned to the values of the NestedDict.
            If a non-iterable or string is passed,
            it will be assigned to each value of the NestedDict.

    Returns:
        NestedDict

    Raises:
        UnequalIterablesError: If the keys and values have different length.

    Examples:
        >>> iterables = [("A", "B"), ("a", "b")]
        >>> NestedDict.from_product(iterables)
        NestedDict({'A': {'a': None, 'b': None}, 'B': {'a': None, 'b': None}})

        Initialize with a single value.

        >>> NestedDict.from_product(iterables, values=0)
        NestedDict({'A': {'a': 0, 'b': 0}, 'B': {'a': 0, 'b': 0}})

        Initialize with different values.

        >>> NestedDict.from_product(iterables, values=[0, 1, 2, 3])
        NestedDict({'A': {'a': 0, 'b': 1}, 'B': {'a': 2, 'b': 3}})

        Passing values with the wrong size will throw an exception.

        >>> NestedDict.from_product(iterables, values=range(99))
        Traceback (most recent call last):
        ...
        more_itertools.recipes.UnequalIterablesError: Iterables have different lengths
    """
    keys = product(*iterables)
    return cls.from_tuples(keys, values)

from_tuples(tuples, values=None) classmethod

Initialize a NestedDict from a list of iterables.

Parameters:

Name Type Description Default
tuples List[Iterable]

Tuples corresponding to the keys of the NestedDict.

required
values Union[Any, Iterable]

If values is an iterable but not a string, its values will become to those of the NestedDict. If a non-iterable or string is passed, it will be assigned to each value of the NestedDict.

None

Returns:

Type Description
T

NestedDict

Raises:

Type Description
UnequalIterablesError

If the keys and values have different length.

Examples:

>>> tuples = [("a", "aa"), ("b",)]
>>> NestedDict.from_tuples(tuples)
NestedDict({'a': {'aa': None}, 'b': None})

Initialize with a single value.

>>> NestedDict.from_tuples(tuples, values=0)
NestedDict({'a': {'aa': 0}, 'b': 0})

Initialize with different values.

>>> NestedDict.from_tuples(tuples, values=[0, 1])
NestedDict({'a': {'aa': 0}, 'b': 1})

Passing values with the wrong size will throw an exception.

>>> NestedDict.from_tuples(tuples, values=range(99))
Traceback (most recent call last):
...
more_itertools.recipes.UnequalIterablesError: Iterables have different lengths...
Source code in ndicts\nested_dict.py
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
@classmethod
def from_tuples(cls, tuples: List[Iterable], values: Union[Any, Iterable] = None) -> T:
    """
    Initialize a NestedDict from a list of iterables.

    Args:
        tuples:
            Tuples corresponding to the keys of the NestedDict.
        values:
            If values is an iterable but not a string,
            its values will become to those of the NestedDict.
            If a non-iterable or string is passed,
            it will be assigned to each value of the NestedDict.

    Returns:
        NestedDict

    Raises:
        UnequalIterablesError: If the keys and values have different length.

    Examples:
        >>> tuples = [("a", "aa"), ("b",)]
        >>> NestedDict.from_tuples(tuples)
        NestedDict({'a': {'aa': None}, 'b': None})

        Initialize with a single value.

        >>> NestedDict.from_tuples(tuples, values=0)
        NestedDict({'a': {'aa': 0}, 'b': 0})

        Initialize with different values.

        >>> NestedDict.from_tuples(tuples, values=[0, 1])
        NestedDict({'a': {'aa': 0}, 'b': 1})

        Passing values with the wrong size will throw an exception.

        >>> NestedDict.from_tuples(tuples, values=range(99))
        Traceback (most recent call last):
        ...
        more_itertools.recipes.UnequalIterablesError: Iterables have different lengths...
    """
    nd = cls()
    if isinstance(values, Iterable) and not isinstance(values, str):
        for key, value in zip_equal(tuples, values):
            nd[key] = value
    else:
        for key in tuples:
            nd[key] = values
    return nd

rows()

Yield the NestedDict row by row.

A row is obtained by adding the leaf value to the sequence of its key.

Notes

This method can be useful to export a NestedDict to a pandas DataFrame.

Yields:

Type Description
Generator

A row of the NestedDict.

Examples:

>>> nd = NestedDict({"a": 0, "b": {"ba": 1}, "c": 2})
>>> [row for row in nd.rows()]
[('a', 0), ('b', 'ba', 1), ('c', 2)]
Source code in ndicts\nested_dict.py
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
def rows(self) -> Generator:
    """
    Yield the NestedDict row by row.

    A row is obtained by adding the leaf value
    to the sequence of its key.

    Notes:
        This method can be useful to export
        a NestedDict to a pandas DataFrame.

    Yields:
        A row of the NestedDict.

    Examples:
        >>> nd = NestedDict({"a": 0, "b": {"ba": 1}, "c": 2})
        >>> [row for row in nd.rows()]
        [('a', 0), ('b', 'ba', 1), ('c', 2)]
    """
    return ((*key, value) for key, value in self.items())

to_dict()

Return a copy as a dictionary.

Source code in ndicts\nested_dict.py
400
401
402
def to_dict(self) -> dict:
    """Return a copy as a dictionary."""
    return deepcopy(self._ndict)