A Python utility belt containing simple tools, a stdlib like feel, and extra batteries
Comprehensive dictionary utilities including enhanced dict classes with set operations, grouping functions, and data structure manipulation tools.
UBelt provides several enhanced dictionary classes that extend standard dict functionality with set operations and auto-vivification.
class UDict(dict):
"""
Enhanced dictionary with set operations and convenience methods.
Supports | & - ^ operators for union, intersection, difference, and symmetric difference.
"""
def __or__(self, other): ... # Union operator
def __and__(self, other): ... # Intersection operator
def __sub__(self, other): ... # Difference operator
def __xor__(self, other): ... # Symmetric difference operator
class AutoDict(dict):
"""
Auto-vivifying dictionary that creates missing intermediate dictionaries.
"""
def __getitem__(self, key): ...
class SetDict(dict):
"""
Dictionary with key-wise set operations on values.
"""
def union(self, *others): ...
def intersection(self, *others): ...
def difference(self, *others): ...
class AutoOrderedDict(collections.OrderedDict):
"""
Auto-vivifying ordered dictionary.
"""
def __getitem__(self, key): ...Core dictionary manipulation functions for merging, filtering, and transforming dictionaries.
def dict_union(*args, **kwargs):
"""
Union of multiple dictionaries.
Args:
*args: Dictionaries to union
**kwargs: Additional key-value pairs
Returns:
dict: Combined dictionary
"""
def dict_isect(*args, **kwargs):
"""
Intersection of dictionaries (common keys).
Args:
*args: Dictionaries to intersect
**kwargs: Additional constraints
Returns:
dict: Dictionary with common keys
"""
def dict_diff(dict1, dict2):
"""
Dictionary difference showing keys that differ.
Args:
dict1 (dict): First dictionary
dict2 (dict): Second dictionary
Returns:
dict: Differences between dictionaries
"""
def dict_subset(dict_, keys, default=NoParam):
"""
Extract subset of dictionary by keys.
Args:
dict_ (dict): Source dictionary
keys: Keys to extract
default: Default value for missing keys
Returns:
dict: Subset dictionary
"""
def dict_hist(items, weights=None, ordered=False, labels=None):
"""
Count discrete occurrences (histogram).
Args:
items: Items to count
weights: Optional weights for each item
ordered (bool): Return OrderedDict if True
labels: Custom labels for items
Returns:
dict: Histogram counts
"""Functions for grouping and organizing data structures.
def group_items(items, key):
"""
Group items by key function or corresponding list.
Args:
items: Items to group
key: Function or list to group by
Returns:
dict: Grouped items
"""
def dzip(items1, items2, cls=dict):
"""
Zip items into dictionary with broadcasting.
Args:
items1: Keys or first items
items2: Values or second items
cls: Dictionary class to use
Returns:
dict: Zipped dictionary
"""
def find_duplicates(items, k=2, key=None):
"""
Find items occurring k+ times.
Args:
items: Items to analyze
k (int): Minimum occurrence count
key: Key function for item comparison
Returns:
list: Items with k+ occurrences
"""
def named_product(**basis):
"""
Named cartesian product of keyword arguments.
Args:
**basis: Named sequences to combine
Returns:
list: List of named combinations
"""
def varied_values(dict_list, min_variations=0):
"""
Find keys with varying values across dictionaries.
Args:
dict_list (list): List of dictionaries
min_variations (int): Minimum variations required
Returns:
dict: Keys and their varying values
"""Functions for transforming dictionary keys and values.
def invert_dict(dict_):
"""
Swap keys and values in dictionary.
Args:
dict_ (dict): Dictionary to invert
Returns:
dict: Inverted dictionary
"""
def map_keys(func, dict_):
"""
Apply function to dictionary keys.
Args:
func: Function to apply to keys
dict_ (dict): Source dictionary
Returns:
dict: Dictionary with transformed keys
"""
def map_vals(func, dict_):
"""
Apply function to dictionary values.
Args:
func: Function to apply to values
dict_ (dict): Source dictionary
Returns:
dict: Dictionary with transformed values
"""
def map_values(func, dict_):
"""
Alias for map_vals.
"""
def sorted_keys(dict_, key=None, reverse=False):
"""
Get sorted dictionary keys.
Args:
dict_ (dict): Source dictionary
key: Sort key function
reverse (bool): Reverse sort order
Returns:
list: Sorted keys
"""
def sorted_vals(dict_, key=None, reverse=False):
"""
Get sorted dictionary values.
Args:
dict_ (dict): Source dictionary
key: Sort key function
reverse (bool): Reverse sort order
Returns:
list: Sorted values
"""
def sorted_values(dict_, key=None, reverse=False):
"""
Alias for sorted_vals.
"""# Dictionary class aliases
udict = UDict # Enhanced dictionary
sdict = SetDict # Set-based dictionary
ddict = collections.defaultdict # Default dictionary
odict = collections.OrderedDict # Ordered dictionaryimport ubelt as ub
# UDict with set operations
d1 = ub.UDict({'a': 1, 'b': 2, 'c': 3})
d2 = ub.UDict({'b': 2, 'c': 4, 'd': 5})
# Union
union = d1 | d2 # {'a': 1, 'b': 2, 'c': 4, 'd': 5}
# Intersection
intersection = d1 & d2 # {'b': 2}
# AutoDict auto-vivification
auto_dict = ub.AutoDict()
auto_dict['level1']['level2']['level3'] = 'value' # Creates intermediate dictsimport ubelt as ub
# Group items by first letter
items = ['apple', 'banana', 'cherry', 'apricot', 'blueberry']
grouped = ub.group_items(items, key=lambda x: x[0])
# Result: {'a': ['apple', 'apricot'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}
# Group by corresponding list
scores = [85, 92, 78, 85, 90]
grades = ['B', 'A', 'C', 'B', 'A']
by_grade = ub.group_items(scores, grades)
# Result: {'B': [85, 85], 'A': [92, 90], 'C': [78]}import ubelt as ub
# Dictionary operations
dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'b': 2, 'c': 4, 'd': 5}
# Union multiple dictionaries
combined = ub.dict_union(dict1, dict2, {'e': 6})
# Transform keys and values
uppercase_keys = ub.map_keys(str.upper, dict1)
doubled_values = ub.map_vals(lambda x: x * 2, dict1)
# Get histogram of values
items = ['a', 'b', 'a', 'c', 'b', 'a']
hist = ub.dict_hist(items) # {'a': 3, 'b': 2, 'c': 1}Install with Tessl CLI
npx tessl i tessl/pypi-ubelt