Transform dictionaries into whatever your heart desires
Project description
transformd
Transform a dictionary
to another dictionary
, but keep the same shape based on a spec
.
What is a spec?
It is a string (or sequence of strings) that specifies what "parts" of the dictionary should be included in a new dictionary
that is returned from the transform
function. A spec
uses dot-notation to traverse into the dictionary
. It can also use indexes if the object is a list.
Examples
from transformd import Transformer
data = {
"library": {
"name": "Main St Library",
"location": {
"street": "123 Main St",
"city": "New York City",
"state": "NY",
},
"books": [
{
"title": "The Grapes of Wrath",
"author": {"first_name": "John", "last_name": "Steinbeck"},
},
{
"title": "Slaughterhouse-Five",
"author": {"first_name": "Kurt", "last_name": "Vonnegut"},
},
],
}
}
assert Transformer(data).transform(spec="library.name") == {
"library": {
"name": "Main St Library"
}
}
assert Transformer(data).transform(spec=("library.name", "library.location.state")) == {
"library": {
"name": "Main St Library",
"location": {
"state": "NY"
},
}
}
assert Transformer(data).transform(spec=("library.books.0.title", "library.books.1")) == {
"library": {
"books": [
{
"title": "The Grapes of Wrath",
},
{
"title": "Slaughterhouse-Five",
"author": {"first_name": "Kurt", "last_name": "Vonnegut"},
},
],
}
}
Why?
I needed this functionality for Unicorn
, but could not find a suitable library. After writing the code, I thought maybe it would be useful for someone else. 🤷
Run tests
rye sync && rye run test
Inspiration
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
transformd-0.1.0.tar.gz
(6.7 kB
view hashes)
Built Distribution
Close
Hashes for transformd-0.1.0-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | a72bb305a9425ff49540abbc4ab0ae767edf33eb8d72868fb809dabcc86cd389 |
|
MD5 | e601759f16a56d10233efae5b880eb2d |
|
BLAKE2b-256 | 56b1a928e0ac558a0516b7465e15d074534d1006530d4b8a601dd72721ce2823 |