dictutils.ops.map_keysΒΆ

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

Transform keys in a mapping using a function.

Parameters:
  • d (Mapping[str, Any]) – Mapping to transform

  • fn (Callable[[str], str]) – Function to apply to keys

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

Return type:

dict[str, Any]

Returns:

New mapping with transformed keys

Example

>>> import json
>>> data = {
...     "first_name": "Alice",
...     "last_name": "Smith",
...     "user_details": {"email_address": "alice@example.com"}
... }
>>> result = map_keys(data, lambda k: k.replace("_", "-"), deep=True)
>>> print(json.dumps(result, indent=4))
{
    "first-name": "Alice",
    "last-name": "Smith",
    "user-details": {
        "email-address": "alice@example.com"
    }
}