8000 GitHub - zaironjacobs/deep-apply: Deep traverse through an object and apply a function on its values.
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

zaironjacobs/deep-apply

Repository files navigation

Deep Apply

PyPI - Python Version PyPI PyPI - License

tests

Deep traverse through an object and apply a function on its values.

Supports the following object types:

  • Dictionaries
  • Lists
  • Sets
  • Tuples
  • Pydantic models

Install

pip install deep-apply

Usage

Apply upper() on values

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']
        }
    }
]

About

Deep traverse through an object and apply a function on its values.

Resources

License

Stars

Watchers

Forks

Languages

0