---
title: "flatten-dict | pypx"
description: "A flexible utility for flattening and unflattening dict-like objects in Python."
canonical_url: "https://pypx.app/packages/flatten-dict"
meta:
  "og:description": "A flexible utility for flattening and unflattening dict-like objects in Python."
  "og:image": "https://pypx.app/_og/d/h_630%2Cc_PackageCard%2Cname_flatten-dict%2Cversion_0.6.0%2Csummary_A%2Bflexible%2Butility%2Bfor%2Bflattening%2Band%2Bunflattening%2Bdict-like%2Bobjects%2Bin%2BPython.%2Clicense_MIT%2BLicense%2Cp_Ii9wYWNrYWdlcy9mbGF0dGVuLWRpY3Qi%2Cs_VwjUA0wPo96YtM9B.png"
  "og:image:height": "630"
  "og:image:type": image/png
  "og:image:width": "1200"
  "og:title": "flatten-dict 0.6.0"
  "twitter:image": "https://pypx.app/_og/d/h_630%2Cc_PackageCard%2Cname_flatten-dict%2Cversion_0.6.0%2Csummary_A%2Bflexible%2Butility%2Bfor%2Bflattening%2Band%2Bunflattening%2Bdict-like%2Bobjects%2Bin%2BPython.%2Clicense_MIT%2BLicense%2Cp_Ii9wYWNrYWdlcy9mbGF0dGVuLWRpY3Qi%2Cs_VwjUA0wPo96YtM9B.png"
---

> Index of every page on this site: [llms.txt](https://pypx.app/llms.txt)

# **flatten-dict**

v0.6.0

A flexible utility for flattening and unflattening dict-like objects in Python.

11 KB Python 3.10+ py3-none-anyMIT License

[**Diff **](https://pypx.app/packages/flatten-dict/diff)

`$ uv add flatten-dict`

# flatten-dict

A flexible utility for flattening and unflattening dict-like objects in Python.

## Introduction

This package provides a function flatten() for flattening dict-like objects in Python (tested with 3.10-3.15). It also provides some key joining methods (reducer), and you can choose the reducer you want or even implement your own reducer. You can also invert the resulting flat dict using unflatten().

## Installation

```bash
pip install flatten-dict
```

## Documentation

##### Flatten

```python
def flatten(d, reducer='tuple', inverse=False, enumerate_types=(), keep_empty_types=()):
    """Flatten `Mapping` object.

    Parameters
    ----------
    d : dict-like object
        The dict that will be flattened.
    reducer : {'tuple', 'path', 'underscore', 'dot', Callable}
        The key joining method. If a `Callable` is given, the `Callable` will be
        used to reduce.
        'tuple': The resulting key will be tuple of the original keys.
        'path': Use `os.path.join` to join keys.
        'underscore': Use underscores to join keys.
        'dot': Use dots to join keys.
    inverse : bool
        Whether you want invert the resulting key and value.
    max_flatten_depth : int
        Maximum depth to merge.
    enumerate_types : Sequence[type]
        Flatten these types using `enumerate`.
        For example, if we set `enumerate_types` to ``(list,)``,
        `list` indices become keys: ``{'a': ['b', 'c']}`` -> ``{('a', 0): 'b', ('a', 1): 'c'}``.
    keep_empty_types : Sequence[type]
        By default, ``flatten({1: 2, 3: {}})`` will give you ``{(1,): 2}``, that is, the key ``3``
        will disappear.
        This is also applied for the types in `enumerate_types`, that is,
        ``flatten({1: 2, 3: []}, enumerate_types=(list,))`` will give you ``{(1,): 2}``.
        If you want to keep those empty values, you can specify the types in `keep_empty_types`:

        >>> flatten({1: 2, 3: {}}, keep_empty_types=(dict,))
        {(1,): 2, (3,): {}}

    Returns
    -------
    flat_dict : dict
    """
```

##### Examples

\>>> from flatten\_dict import flatten >>> from pprint import pprint >>> normal\_dict = { ... 'a': '0', ... 'b': { ... 'a': '1.0', ... 'b': '1.1', ... }, ... 'c': { ... 'a': '2.0', ... 'b': { ... 'a': '2.1.0', ... 'b': '2.1.1', ... }, ... }, ... } >>> pprint(flatten(normal\_dict)) {('a',): '0', ('b', 'a'): '1.0', ('b', 'b'): '1.1', ('c', 'a'): '2.0', ('c', 'b', 'a'): '2.1.0', ('c', 'b', 'b'): '2.1.1'} >>> pprint(flatten(normal\_dict, reducer='path')) {'a': '0', 'b/a': '1.0', 'b/b': '1.1', 'c/a': '2.0', 'c/b/a': '2.1.0', 'c/b/b': '2.1.1'} >>> pprint(flatten(normal\_dict, reducer='path', inverse=True)) {'0': 'a', '1.0': 'b/a', '1.1': 'b/b', '2.0': 'c/a', '2.1.0': 'c/b/a', '2.1.1': 'c/b/b'} >>> pprint(flatten(normal\_dict, reducer='path', max\_flatten\_depth=2)) {'a': '0', 'b/a': '1.0', 'b/b': '1.1', 'c/a': '2.0', 'c/b': {'a': '2.1.0', 'b': '2.1.1'}}

The `reducer` parameter supports 'tuple', 'path', 'underscore', 'dot' and `Callable`. We can customize the reducer using a function:

\>>> def underscore\_reducer(k1, k2): ... if k1 is None: ... return k2 ... else: ... return k1 + "\_" + k2 ... >>> pprint(flatten(normal\_dict, reducer=underscore\_reducer)) {'a': '0', 'b\_a': '1.0', 'b\_b': '1.1', 'c\_a': '2.0', 'c\_b\_a': '2.1.0', 'c\_b\_b': '2.1.1'}

There is also a factory function `make_reducer()` to help you create customized reducer. The function currently only supports customized delimiter:

\>>> from flatten\_dict.reducers import make\_reducer >>> pprint(flatten(normal\_dict, reducer=make\_reducer(delimiter='\_'))) {'a': '0', 'b\_a': '1.0', 'b\_b': '1.1', 'c\_a': '2.0', 'c\_b\_a': '2.1.0', 'c\_b\_b': '2.1.1'}

If we have some iterable (e.g., `list`) in the `dict`, we will normally get this:

\>>> flatten({'a': \[1, 2, 3], 'b': 'c'}) {('a',): \[1, 2, 3], ('b',): 'c'}

If we want to use its indices as keys, then we can use the parameter `enumerate_types`:

\>>> flatten({'a': \[1, 2, 3], 'b': 'c'}, enumerate\_types=(list,)) {('a', 0): 1, ('a', 1): 2, ('a', 2): 3, ('b',): 'c'}

We can even flatten a `list` directly:

\>>> flatten(\[1, 2, 3], enumerate\_types=(list,)) {(0,): 1, (1,): 2, (2,): 3}

If there is an empty dict in the values, by default, it will disappear after flattened:

\>>> flatten({1: 2, 3: {}}) {(1,): 2}

We can keep the empty dict in the result using keep\_empty\_types=(dict,):

\>>> flatten({1: 2, 3: {}}, keep\_empty\_types=(dict,)) {(1,): 2, (3,): {}}

##### Unflatten

```python
def unflatten(d, splitter='tuple', inverse=False, allow_non_leaf_values=False):
    """Unflatten dict-like object.

    Parameters
    ----------
    d : dict-like object
        The dict that will be unflattened.
    splitter : {'tuple', 'path', 'underscore', 'dot', Callable}
        The key splitting method. If a Callable is given, the Callable will be
        used to split `d`.
        'tuple': Use each element in the tuple key as the key of the unflattened dict.
        'path': Use `pathlib.Path.parts` to split keys.
        'underscore': Use underscores to split keys.
        'dot': Use dots to split keys.
    inverse : bool
        Whether you want to invert the key and value before flattening.
    allow_non_leaf_values : bool
        Whether a key may be nested inside the value of a shorter key, e.g.
        ``unflatten({('a',): {'existing': 0}, ('a', 'b'): 2})``. If False (the
        default), that raises ``ValueError``. If True, the deeper key is set on
        the shorter key's value, which mutates that value in place, so `d` and
        the returned dict share it.

    Returns
    -------
    unflattened_dict : dict
    """
```

##### Examples

\>>> from pprint import pprint >>> from flatten\_dict import unflatten >>> flat\_dict = { ... ('a',): '0', ... ('b', 'a'): '1.0', ... ('b', 'b'): '1.1', ... ('c', 'a'): '2.0', ... ('c', 'b', 'a'): '2.1.0', ... ('c', 'b', 'b'): '2.1.1', ... } >>> pprint(unflatten(flat\_dict)) {'a': '0', 'b': {'a': '1.0', 'b': '1.1'}, 'c': {'a': '2.0', 'b': {'a': '2.1.0', 'b': '2.1.1'}}} >>> flat\_dict = { ... 'a': '0', ... 'b/a': '1.0', ... 'b/b': '1.1', ... 'c/a': '2.0', ... 'c/b/a': '2.1.0', ... 'c/b/b': '2.1.1', ... } >>> pprint(unflatten(flat\_dict, splitter='path')) {'a': '0', 'b': {'a': '1.0', 'b': '1.1'}, 'c': {'a': '2.0', 'b': {'a': '2.1.0', 'b': '2.1.1'}}} >>> flat\_dict = { ... '0': 'a', ... '1.0': 'b/a', ... '1.1': 'b/b', ... '2.0': 'c/a', ... '2.1.0': 'c/b/a', ... '2.1.1': 'c/b/b', ... } >>> pprint(unflatten(flat\_dict, splitter='path', inverse=True)) {'a': '0', 'b': {'a': '1.0', 'b': '1.1'}, 'c': {'a': '2.0', 'b': {'a': '2.1.0', 'b': '2.1.1'}}}

The `splitter` parameter supports 'tuple', 'path', 'underscore', 'dot' and `Callable`. We can customize the reducer using a function:

\>>> def underscore\_splitter(flat\_key): ... return flat\_key.split("\_") ... >>> flat\_dict = { ... 'a': '0', ... 'b\_a': '1.0', ... 'b\_b': '1.1', ... 'c\_a': '2.0', ... 'c\_b\_a': '2.1.0', ... 'c\_b\_b': '2.1.1', ... } >>> pprint(unflatten(flat\_dict, splitter=underscore\_splitter)) {'a': '0', 'b': {'a': '1.0', 'b': '1.1'}, 'c': {'a': '2.0', 'b': {'a': '2.1.0', 'b': '2.1.1'}}}

There is also a factory function `make_splitter()` to help you create customized splitter. The function currently only supports customized delimiter:

\>>> from flatten\_dict.splitters import make\_splitter >>> pprint(unflatten(flat\_dict, splitter=make\_splitter(delimiter='\_'))) {'a': '0', 'b': {'a': '1.0', 'b': '1.1'}, 'c': {'a': '2.0', 'b': {'a': '2.1.0', 'b': '2.1.1'}}}

## **Details **

<dl>

<dt>Version</dt>
<dd>0.6.0</dd>

<dt>License</dt>
<dd>MIT License</dd>

<dt>Python</dt>
<dd>&lt;4.0,&gt;=3.10</dd>

<dt>Maintainer</dt>
<dd>Ian Lin</dd></dl>

## **Links**

- [Homepage](https://github.com/ianlini/flatten-dict)
- [Repository](https://github.com/ianlini/flatten-dict)
- [View on PyPI](https://pypi.org/project/flatten-dict/)

## **Release Cadence **

**3**

releases in the past year

avg 279 days between releases

## **Maintainers **

- Ian Lin · [you@example.com](mailto:you@example.com)

```json
{"@context":"https://schema.org","@graph":[{"@id":"https://pypx.app/#website","@type":"WebSite","description":"The Python Package Index, reimagined. Fast search, dependency insights, download trends, and changelogs — all in one place.","name":"pypx","url":"https://pypx.app/"},{"@id":"https://pypx.app/packages/flatten-dict#webpage","@type":"WebPage","description":"A flexible utility for flattening and unflattening dict-like objects in Python.","name":"flatten-dict","url":"https://pypx.app/packages/flatten-dict","isPartOf":{"@id":"https://pypx.app/#website"},"potentialAction":[{"@type":"ReadAction","target":["https://pypx.app/packages/flatten-dict"]}]},{"@id":"https://pypx.app/packages/flatten-dict#/schema/software-application/1","@type":"SoftwareApplication","applicationCategory":"DeveloperApplication","description":"A flexible utility for flattening and unflattening dict-like objects in Python.","license":"MIT License","name":"flatten-dict","softwareVersion":"0.6.0"}]}
```

## Sitemap

See the full [sitemap](https://pypx.app/sitemap.md) for all pages.
