Skip to main content

Unflatten dict to dict with nested dict/arrays

Project description

Latest Version Python versions build status

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 take 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

History

Release 0.1.1 (2021-08-16)

Nits

  • Fix backslashes in docstrings

Packaging

  • PEP517-ize the packaging
  • Use setuptools-scm to maintain version numbers

Testing

  • Test under Python 3.7, 3.8, 3.9 and PyPy 3.7. Drop testing for Python 3.4 & 3.5.
  • Pin pip version for pypy2 (see pip #8653)
  • Clean up and modernize the tox lint and coverage environments

Release 0.1 (2018-01-17)

No code changes.

This package is now deemed “production ready” (though your mileage may vary.)

Release 0.1b1 (2018-01-09)

Initial release.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for unflatten, version 0.1.1
Filename, size File type Python version Upload date Hashes
Filename, size unflatten-0.1.1-py2.py3-none-any.whl (5.1 kB) File type Wheel Python version py2.py3 Upload date Hashes View
Filename, size unflatten-0.1.1.tar.gz (6.8 kB) File type Source Python version None Upload date Hashes View

Supported by

AWS AWS Cloud computing Datadog Datadog Monitoring DigiCert DigiCert EV certificate Facebook / Instagram Facebook / Instagram PSF Sponsor Fastly Fastly CDN Google Google Object Storage and Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Salesforce Salesforce PSF Sponsor Sentry Sentry Error logging StatusPage StatusPage Status page