Python flatten dictionaries

  1. For providing universal configuration files
  2. To have a model that is independent of representation
  3. All data is fundamentally hierarchical
  4. Can switch between toml, yaml, xml, or properties

All one need to know may be here: SOF

  1. Lot of sample code
  2. Other suggestions
  3. etc.

Google question that is good for this

is there a flatten method to flatten hierarchical dictionaries?

Search for: is there a flatten method to flatten hierarchical dictionaries?

github flatten-dict homepage

Search for: github flatten-dict homepage

flatten-dict homepage


from flatten_dict import flatten

nested_dict = {
    'a': 1,
    'b': {
        'c': 2,
        'd': {
            'e': 3
        }
    }
}

flat = flatten(nested_dict, reducer='dot')
print(flat)

[database]
type = "sqlite"

[database.settings]
path = "/path/to/database/file.db"

[database.settings.options]
timeout = 30
cache_size = 5000

Notice how "."s are used in section headers

  1. 1. "." are how the hierarchy is established in toml
  2. 2. they are allowed in section headers
  3. 3. Through those section headers form a hierarchy
  4. 4. Generally the "." are not allowed in keys
  5. 5. If you want, you have to put them in double quotes
  6. 6. The section headers are broken down into hierarchical dictionaries in memory
  7. 7. But the double quote keys with "."s are retained as they are

{
    "database": {
        "type": "sqlite",
        "settings": {
            "path": "/path/to/database/file.db",
            "options": {
                "timeout": 30,
                "cache_size": 5000
            }
        }
    }
}