Deep traverse through an object and apply a function on its values.
Supports the following object types:
- Dictionaries
- Lists
- Sets
- Tuples
- Pydantic models
pip install deep-apply
import deep_apply
# 1. Create your callback function.
def to_upper(value, **kwargs):
"""
To uppercase.
"""
# Other arguments passed to the callback function:
# key: str = kwargs["key"]
# depth_level: int = kwargs["depth_level"]
# depth_key: str = kwargs["depth_key"]
# Apply upper() and return the value
if isinstance(value, str):
return value.upper()
# Always return the unedited value
return value
# 2. Your data.
data = [
{
"id": "pZnZMffPCpJx",
"name": "John Doe",
"hobbies": {
"sport": ["football", "tennis"],
"music": ["singing", "guitar", "piano"],
},
}
]
# 3. Run apply().
data = deep_apply.apply(data=data, func=to_upper)
[
{
'id': 'PZNZMFFPCPJX',
'name': 'JOHN DOE',
'hobbies': {
'sport': ['FOOTBALL', 'TENNIS'],
'music': ['SINGING', 'GUITAR', 'PIANO']
}
}
]