Skip to content

Python library to unpack flat dictionaries to a dict with nested dicts and/or lists

License

Notifications You must be signed in to change notification settings

dairiki/unflatten

Folders and files

NameName
Last commit message
Last commit date

Latest commit

c1a36d0 · Sep 5, 2024

History

37 Commits
Sep 5, 2024
Sep 5, 2024
Feb 9, 2023
Feb 9, 2023
Feb 9, 2023
Sep 5, 2024
Jan 9, 2018
Sep 5, 2024
May 5, 2023
Feb 9, 2023
Feb 9, 2023
Feb 9, 2023
Sep 5, 2024

Repository files navigation

unflatten - convert flat dict to nested dict/array

Latest Version Python versions CI test status Trackgit Views

Description

This package provides a function which can unpack a flat dictionary into a structured dict with nested sub-dicts and/or sub-lists.

Development takes place on github. The package is installable from PyPI.

Synopsis

Nested dicts:

>>> from unflatten import unflatten

>>> unflatten({'foo.bar': 'val'})
{'foo': {'bar': 'val'}}

Nested list:

>>> unflatten({'foo[0]': 'x', 'foo[1]': 'y'})
{'foo': ['x', 'y']}

Nested lists and dicts, intermixed:

>>> unflatten({
...     'foo[0][0]': 'a',
...     'foo[0][1]': 'b',
...     'foo[1].x': 'c',
...      })
{'foo': [['a', 'b'], {'x': 'c'}]}

Notes

Unflatten takes a single argument which should either be a dict (or an object with a dict-like .items() or .iteritems() method) or a sequence of (key, value) pairs. All keys in the dict or sequence must be strings. (Under python 2, keys must be instances of basestring; under python 3, keys just be instances of str.)

Unflatten always returns a dict. By way of example:

>>> unflatten([('[0]', 'x')])
{'': ['x']}

For list-valued nodes, all indexes must be present in the input (flattened) mapping, otherwise a ValueError will be thrown:

>>> unflatten({'a[0]': 'x', 'a[2]': 'y'})
Traceback (most recent call last):
...
ValueError: missing key 'a[1]'

See Also

The morph and flattery packages purport to implement similar functions.

Authors

Jeff Dairiki

About

Python library to unpack flat dictionaries to a dict with nested dicts and/or lists

Resources

License

Stars

Watchers

Forks

Sponsor this project

Packages

No packages published

Languages