Restructure dictionary values by key
Project description
Dictionary Restructure Tool
Project
This project implements in Python a function called restructure()
:
def restructure(data: dict, specification: dict):
...
It is useful to restructure where keys are in a dictionary, for example to upgrade a configuration file to a new schema.
Usage
from restructure import restructure
Moving Keys
To move a nested dictionary to the top-level:
input_data = {
'key1': {
'key2': {
'key3': 'value',
}
}
}
specification = {
'key1.key2.key3': 'key1',
}
output = restructure(input_data, specification)
assert output == {
'key1': 'value',
}
or the opposite:
input_data = {
'key1': 'value'
}
specification = {
'key1': 'key1.key2.key3',
}
output = restructure(input_data, specification)
assert output == {
'key1': {
'key2': {
'key3': 'value',
}
}
}
Or to swap keys:
input_data = {
'key1': {
'key2': 'value1',
},
'key3': {
'key4': 'value2',
},
}
specification = {
'key1.key2': 'key3.key4',
'key3.key4': 'key1.key2',
}
output = restructure(input_data, specification)
assert output == {
'key1': {
'key2': 'value2',
},
'key3': {
'key4': 'value1',
},
}
Copying Keys
Keys can be copied using sets of key-paths:
input_data = {
'key1': {
'key2': {
'key3': 'value1',
}
}
}
specification = {
'key1.key2.key3': {'key1.key2.key3.key4', 'key1.key2.key5', 'key1.key6', 'key7'},
}
output = restructure(input_data, specification)
assert output == {
'key1': {
'key2': {
'key3': {
'key4': 'value1',
},
'key5': 'value1',
},
'key6': 'value1',
},
'key7': 'value1',
}
Merging Keys
Keys which contain dictionaries or equivalent values can be merged:
input_data = {
'key1': {
'key2': {
'key3': 'value1',
}
},
'key4': {
'key5': 'value2',
},
'key6': 'value1',
}
specification = {
'key4': 'key1.key2',
'key6': 'key1.key2.key3'
}
output = restructure(input_data, specification)
assert output == {
'key1': {
'key2': {
'key3': 'value1',
'key5': 'value2',
}
},
}
For Developers
- Follows Semantic Versioning 2.0.0
- Follows this package structure
Testing
To run unit tests, run the following command from the project root directory:
python -m unittest
Packaging
Before packaging, update the version number in pyproject.toml
To package & upload the project, run the following commands from the project root directory:
python -m build
python -m twine upload dist/*
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for restructure-0.1.1-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | fa5caba375d19bf3c242c5ecf6dc1b06633203979126eac4bee8e88658c125c1 |
|
MD5 | 32560b454df4df5b3bd9c9695f5878c7 |
|
BLAKE2b-256 | 56d68fa1e788e035658216c99355f6c1d913f3c5fd602d224825f76381ea8c92 |