CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-toolz

List processing tools and functional utilities

Overview
Eval results
Files

dicttoolz.mddocs/

Dictionary Operations

Immutable dictionary manipulation functions including merging, filtering, mapping, and nested access operations. All functions return new dictionaries without modifying input dictionaries, following functional programming principles.

Capabilities

Dictionary Combination

Functions for combining multiple dictionaries in various ways.

def merge(*dicts, **kwargs):
    """
    Merge collection of dictionaries into a single dictionary.
    
    Parameters:
    - *dicts: dictionaries to merge (later ones take precedence)
    - factory: dict-like constructor for result type (optional)
    
    Returns:
    New dictionary with merged key-value pairs
    """

def merge_with(func, *dicts, **kwargs):
    """
    Merge dictionaries and apply function to combined values.
    
    When multiple dictionaries contain the same key, all values
    for that key are passed to func as a list.
    
    Parameters:
    - func: function to apply to combined values (takes list, returns value)
    - *dicts: dictionaries to merge
    - factory: dict-like constructor for result type (optional)
    
    Returns:
    New dictionary with func applied to combined values
    """

Dictionary Transformation

Functions for applying transformations to dictionary keys, values, or items.

def valmap(func, d, factory=dict):
    """
    Apply function to all values in dictionary.
    
    Parameters:
    - func: function to apply to each value
    - d: input dictionary
    - factory: constructor for result dictionary type
    
    Returns:
    New dictionary with transformed values
    """

def keymap(func, d, factory=dict):
    """
    Apply function to all keys in dictionary.
    
    Parameters:
    - func: function to apply to each key
    - d: input dictionary
    - factory: constructor for result dictionary type
    
    Returns:
    New dictionary with transformed keys
    """

def itemmap(func, d, factory=dict):
    """
    Apply function to all (key, value) pairs in dictionary.
    
    Parameters:
    - func: function taking (key, value) and returning (new_key, new_value)
    - d: input dictionary
    - factory: constructor for result dictionary type
    
    Returns:
    New dictionary with transformed items
    """

Dictionary Filtering

Functions for filtering dictionaries based on keys, values, or items.

def valfilter(predicate, d, factory=dict):
    """
    Filter dictionary items by values.
    
    Parameters:
    - predicate: function that returns True/False for each value
    - d: input dictionary
    - factory: constructor for result dictionary type
    
    Returns:
    New dictionary containing only items where predicate(value) is True
    """

def keyfilter(predicate, d, factory=dict):
    """
    Filter dictionary items by keys.
    
    Parameters:
    - predicate: function that returns True/False for each key
    - d: input dictionary
    - factory: constructor for result dictionary type
    
    Returns:
    New dictionary containing only items where predicate(key) is True
    """

def itemfilter(predicate, d, factory=dict):
    """
    Filter dictionary items by (key, value) pairs.
    
    Parameters:
    - predicate: function that returns True/False for each (key, value) pair
    - d: input dictionary
    - factory: constructor for result dictionary type
    
    Returns:
    New dictionary containing only items where predicate(key, value) is True
    """

Dictionary Manipulation

Functions for adding, removing, and updating dictionary entries.

def assoc(d, key, value, factory=dict):
    """
    Return new dictionary with key-value pair added/updated.
    
    Parameters:
    - d: input dictionary
    - key: key to associate with value
    - value: value to associate with key
    - factory: constructor for result dictionary type
    
    Returns:
    New dictionary with key mapped to value
    """

def dissoc(d, *keys, **kwargs):
    """
    Return new dictionary with specified keys removed.
    
    Parameters:
    - d: input dictionary
    - *keys: keys to remove from dictionary
    - factory: constructor for result dictionary type (optional)
    
    Returns:
    New dictionary with specified keys removed
    """

def assoc_in(d, keys, value, factory=dict):
    """
    Return new dictionary with nested key-value pair added/updated.
    
    Creates nested dictionary structure as needed.
    
    Parameters:
    - d: input dictionary (possibly nested)
    - keys: sequence of keys defining path to nested value
    - value: value to set at nested location
    - factory: constructor for result dictionary type
    
    Returns:
    New nested dictionary with value set at specified path
    """

def update_in(d, keys, func, default=None, factory=dict):
    """
    Update value in nested dictionary by applying function.
    
    Parameters:
    - d: input dictionary (possibly nested)
    - keys: sequence of keys defining path to nested value
    - func: function to apply to current value at path
    - default: default value if path doesn't exist
    - factory: constructor for result dictionary type
    
    Returns:
    New nested dictionary with updated value at path
    """

def get_in(keys, coll, default=None, no_default=False):
    """
    Get value from nested dictionary/collection.
    
    Access nested value using sequence of keys: coll[keys[0]][keys[1]]...[keys[n]]
    
    Parameters:
    - keys: sequence of keys defining path to nested value
    - coll: nested dictionary or collection
    - default: value to return if path doesn't exist
    - no_default: if True, raise KeyError when path doesn't exist
    
    Returns:
    Value at nested path, or default if path doesn't exist
    """

Usage Examples

Dictionary Merging and Combination

from toolz import merge, merge_with
from operator import add

# Basic merging
config_defaults = {'host': 'localhost', 'port': 8080, 'debug': False}
user_config = {'port': 3000, 'debug': True}
config = merge(config_defaults, user_config)
# {'host': 'localhost', 'port': 3000, 'debug': True}

# Merge with function to combine values
sales_q1 = {'apples': 100, 'oranges': 80, 'bananas': 60}
sales_q2 = {'apples': 120, 'oranges': 70, 'bananas': 90}
total_sales = merge_with(add, sales_q1, sales_q2)
# {'apples': 220, 'oranges': 150, 'bananas': 150}

# Merge multiple dictionaries
results = merge_with(
    lambda values: sum(values) / len(values),  # average
    {'score': 85}, {'score': 90}, {'score': 78}
)
# {'score': 84.33333333333333}

Dictionary Transformation

from toolz import valmap, keymap, itemmap

# Transform values
prices = {'apple': 1.20, 'banana': 0.80, 'orange': 1.50}
prices_cents = valmap(lambda x: int(x * 100), prices)
# {'apple': 120, 'banana': 80, 'orange': 150}

# Transform keys
data = {'firstName': 'John', 'lastName': 'Doe', 'emailAddress': 'john@example.com'}
snake_case = keymap(lambda k: ''.join('_' + c.lower() if c.isupper() else c for c in k).lstrip('_'), data)
# {'first_name': 'John', 'last_name': 'Doe', 'email_address': 'john@example.com'}

# Transform both keys and values
inventory = {'APPLES': 50, 'BANANAS': 30, 'ORANGES': 25}
formatted = itemmap(lambda k, v: (k.lower().capitalize(), f"{v} units"), inventory)
# {'Apples': '50 units', 'Bananas': '30 units', 'Oranges': '25 units'}

Dictionary Filtering

from toolz import valfilter, keyfilter, itemfilter

# Filter by values
scores = {'alice': 85, 'bob': 92, 'charlie': 78, 'diana': 96}
high_scores = valfilter(lambda score: score >= 90, scores)
# {'bob': 92, 'diana': 96}

# Filter by keys
data = {'user_name': 'john', 'user_email': 'john@example.com', 'temp_token': 'abc123', 'user_id': 42}
user_data = keyfilter(lambda key: key.startswith('user_'), data)
# {'user_name': 'john', 'user_email': 'john@example.com', 'user_id': 42}

# Filter by items (key-value pairs)
products = {'laptop': 1200, 'mouse': 25, 'keyboard': 80, 'monitor': 300}
affordable = itemfilter(lambda k, v: v <= 100, products)
# {'mouse': 25, 'keyboard': 80}

Nested Dictionary Operations

from toolz import assoc_in, update_in, get_in

# Working with nested data
user = {
    'name': 'Alice',
    'profile': {
        'age': 30,
        'address': {
            'city': 'New York',
            'country': 'USA'
        }
    }
}

# Access nested values
city = get_in(['profile', 'address', 'city'], user)
# 'New York'

# Set nested values (creates structure as needed)
updated_user = assoc_in(user, ['profile', 'address', 'zipcode'], '10001')
# Adds zipcode to the nested address

# Update nested values with function
aged_user = update_in(user, ['profile', 'age'], lambda age: age + 1)
# Increments age from 30 to 31

# Handle missing paths gracefully
phone = get_in(['profile', 'contact', 'phone'], user, 'No phone available')
# 'No phone available' (since path doesn't exist)

Advanced Dictionary Patterns

from toolz import pipe, merge, valmap, keyfilter, assoc

# Complex data processing pipeline
raw_data = {
    'users': [
        {'name': 'Alice', 'age': 30, 'active': True},
        {'name': 'Bob', 'age': 25, 'active': False},
        {'name': 'Charlie', 'age': 35, 'active': True}
    ]
}

# Process user data
processed = pipe(
    raw_data,
    lambda d: assoc(d, 'active_users', [u for u in d['users'] if u['active']]),
    lambda d: assoc(d, 'user_count', len(d['users'])),
    lambda d: assoc(d, 'avg_age', sum(u['age'] for u in d['users']) / len(d['users'])),
    lambda d: keyfilter(lambda k: k != 'users', d)  # Remove original users list
)
# {
#   'active_users': [{'name': 'Alice', 'age': 30, 'active': True}, ...],
#   'user_count': 3,
#   'avg_age': 30.0
# }

Configuration Management

from toolz import merge, assoc_in, get_in

# Application configuration with defaults and overrides
default_config = {
    'database': {
        'host': 'localhost',
        'port': 5432,
        'name': 'myapp'
    },
    'api': {
        'timeout': 30,
        'retries': 3
    },
    'features': {
        'caching': True,
        'logging': True
    }
}

# Environment-specific overrides
production_overrides = {
    'database': {
        'host': 'prod-db.example.com',
        'port': 5432
    },
    'api': {
        'timeout': 60
    },
    'features': {
        'caching': True
    }
}

# Merge configurations
config = merge(default_config, production_overrides)

# Update specific nested values
config = assoc_in(config, ['database', 'ssl'], True)
config = assoc_in(config, ['api', 'rate_limit'], 1000)

# Access configuration values
db_host = get_in(['database', 'host'], config)
api_timeout = get_in(['api', 'timeout'], config)

Install with Tessl CLI

npx tessl i tessl/pypi-toolz

docs

curried.md

dicttoolz.md

functoolz.md

index.md

itertoolz.md

sandbox.md

tile.json