Python flatten dictionaries
satya - 3/5/2024, 8:16:20 AM
Why do I need this?
- For providing universal configuration files
- To have a model that is independent of representation
- All data is fundamentally hierarchical
- Can switch between toml, yaml, xml, or properties
satya - 3/5/2024, 8:16:56 AM
All one need to know may be here: SOF
satya - 3/5/2024, 8:17:25 AM
what you have here
- Lot of sample code
- Other suggestions
- etc.
satya - 3/5/2024, 8:17:44 AM
Google question that is good for this
Google question that is good for this
satya - 3/5/2024, 8:17:52 AM
is there a flatten method to flatten hierarchical dictionaries?
is there a flatten method to flatten hierarchical dictionaries?
Search for: is there a flatten method to flatten hierarchical dictionaries?
satya - 3/5/2024, 8:23:52 AM
github flatten-dict homepage
github flatten-dict homepage
satya - 3/5/2024, 9:49:14 AM
Example using flatten-dict
from flatten_dict import flatten
nested_dict = {
'a': 1,
'b': {
'c': 2,
'd': {
'e': 3
}
}
}
flat = flatten(nested_dict, reducer='dot')
print(flat)
satya - 3/5/2024, 10:23:18 AM
Nature of hierarchy in toml
[database]
type = "sqlite"
[database.settings]
path = "/path/to/database/file.db"
[database.settings.options]
timeout = 30
cache_size = 5000
satya - 3/5/2024, 10:23:47 AM
Notice how "."s are used in section headers
Notice how "."s are used in section headers
satya - 3/5/2024, 10:26:03 AM
Some toml rules
- 1. "." are how the hierarchy is established in toml
- 2. they are allowed in section headers
- 3. Through those section headers form a hierarchy
- 4. Generally the "." are not allowed in keys
- 5. If you want, you have to put them in double quotes
- 6. The section headers are broken down into hierarchical dictionaries in memory
- 7. But the double quote keys with "."s are retained as they are
satya - 3/5/2024, 10:26:37 AM
So the above will look like this in python, the sections expanded to nested dictionaries
{
"database": {
"type": "sqlite",
"settings": {
"path": "/path/to/database/file.db",
"options": {
"timeout": 30,
"cache_size": 5000
}
}
}
}