dictutils.ops.map_valuesΒΆ

dictutils.ops.map_values(d, fn, *, deep=False, predicate=None)[source]ΒΆ

Transform values in a mapping using a function.

Parameters:
  • d (Any) – Object to transform

  • fn (Callable[[Any], Any]) – Function to apply to values

  • deep (bool) – Whether to recursively transform nested mappings

  • predicate (Optional[Callable[[Any, Any], bool]]) – Optional function to filter which values to transform

Return type:

Any

Returns:

New object with transformed values

Example

>>> import json
>>> data = {"user": {"age": 30, "score": 95.5, "name": "Alice"}}
>>> result = map_values(data, lambda x: x * 2 if isinstance(x, (int, float)) else x,
...                    deep=True)
>>> print(json.dumps(result, indent=4))
{
    "user": {
        "age": 60,
        "score": 191.0,
        "name": "Alice"
    }
}