def test_ordered_dict_output(): assert dict_tools.reverse_with_set_values({1: 2, 3: 4, 'meow': 2}, sort=True) == \ nifty_collections.OrderedDict([(2, {1, 'meow'}), (4, {3})]) assert dict_tools.reverse_with_set_values({1: 2, 3: 4, 'meow': 2}, sort=lambda x: -x) == \ nifty_collections.OrderedDict([(4, {3}), (2, {1, 'meow'})])
def reverse_with_set_values(d, sort=False): ''' Reverse the dict, with the values of the new dict being sets. Example: reverse_with_set_values({1: 2, 3: 4, 'meow': 2}) == \ {2: {1, 'meow'}, 4: {3}} Instead of a dict you may also input a tuple in which the first item is an iterable and the second item is either a key function or an attribute name. A dict will be constructed from these and used. If you'd like the result dict to be sorted, pass `sort=True`, and you'll get a sorted `OrderedDict`. You can also specify the sorting key function or attribute name as the `sort` argument. ''' ### Pre-processing input: ################################################# # # if hasattr(d, 'items'): # `d` is a dict fixed_dict = d else: # `d` is not a dict assert cute_iter_tools.is_iterable(d) and len(d) == 2 iterable, key_function_or_attribute_name = d assert cute_iter_tools.is_iterable(iterable) key_function = comparison_tools.process_key_function_or_attribute_name( key_function_or_attribute_name ) fixed_dict = {key: key_function(key) for key in iterable} # # ### Finished pre-processing input. ######################################## new_dict = {} for key, value in fixed_dict.iteritems(): if value not in new_dict: new_dict[value] = [] new_dict[value].append(key) # Making into sets: for key, value in new_dict.copy().iteritems(): new_dict[key] = set(value) if sort: from python_toolbox import nifty_collections ordered_dict = nifty_collections.OrderedDict(new_dict) if isinstance(sort, (collections.Callable, basestring)): key_function = comparison_tools. \ process_key_function_or_attribute_name(sort) else: assert sort is True key_function = None ordered_dict.sort(key_function) return ordered_dict else: return new_dict
def get_equivalence_classes(iterable, key=None, container=set, *, use_ordered_dict=False, sort_ordered_dict=False): ''' Divide items in `iterable` to equivalence classes, using the key function. Each item will be put in a set with all other items that had the same result when put through the `key` function. Example: >>> get_equivalence_classes(range(10), lambda x: x % 3) {0: {0, 9, 3, 6}, 1: {1, 4, 7}, 2: {8, 2, 5}} Returns a `dict` with keys being the results of the function, and the values being the sets of items with those values. Alternate usages: Instead of a key function you may pass in an attribute name as a string, and that attribute will be taken from each item as the key. Instead of an iterable and a key function you may pass in a `dict` (or similar mapping) into `iterable`, without specifying a `key`, and the value of each item in the `dict` will be used as the key. Example: >>> get_equivalence_classes({1: 2, 3: 4, 'meow': 2}) {2: {1, 'meow'}, 4: {3}} If you'd like the result to be in an `OrderedDict`, specify `use_ordered_dict=True`, and the items will be ordered according to insertion order. If you'd like that `OrderedDict` to be sorted, pass in `sort_ordered_dict=True`. (It automatically implies `use_ordered_dict=True`.) You can also pass in a sorting key function or attribute name as the `sort_ordered_dict` argument. ''' from python_toolbox import comparison_tools ### Pre-processing input: ################################################# # # if key is None: if isinstance(iterable, collections.abc.Mapping): d = iterable else: try: d = dict(iterable) except ValueError: raise Exception( "You can't put in a non-dict without also supplying a " "`key` function. We need to know which key to use." ) else: # key is not None assert cute_iter_tools.is_iterable(iterable) key_function = comparison_tools.process_key_function_or_attribute_name( key ) d = {key: key_function(key) for key in iterable} # # ### Finished pre-processing input. ######################################## if use_ordered_dict or sort_ordered_dict: from python_toolbox import nifty_collections new_dict = nifty_collections.OrderedDict() else: new_dict = {} for key, value in d.items(): new_dict.setdefault(value, []).append(key) # Making into desired container: for key, value in new_dict.copy().items(): new_dict[key] = container(value) if sort_ordered_dict: if isinstance(sort_ordered_dict, (collections.abc.Callable, str)): key_function = comparison_tools. \ process_key_function_or_attribute_name(sort_ordered_dict) new_dict.sort(key_function) elif sort_ordered_dict is True: new_dict.sort() return new_dict else: return new_dict
def test_ordered_dict_output(): # Insertion order: assert get_equivalence_classes( nifty_collections.OrderedDict(((1, 2), (3, 4), ('meow', 2))), use_ordered_dict=True) == \ nifty_collections.OrderedDict([(2, set((1, 'meow'))), (4, set((3,)))]) assert get_equivalence_classes( nifty_collections.OrderedDict((('meow', 2), (1, 2), (3, 4))), use_ordered_dict=True) == \ nifty_collections.OrderedDict([(2, set((1, 'meow'))), (4, set((3,)))]) assert get_equivalence_classes( nifty_collections.OrderedDict(((3, 4), (1, 2), ('meow', 2))), use_ordered_dict=True) == \ nifty_collections.OrderedDict([(4, set((3,))), (2, set((1, 'meow',)))]) assert get_equivalence_classes( nifty_collections.OrderedDict(((1, 2), (3, 4), ('meow', 2))), container=tuple, use_ordered_dict=True) == \ nifty_collections.OrderedDict([(2, (1, 'meow')), (4, (3,))]) assert get_equivalence_classes( nifty_collections.OrderedDict((('meow', 2), (1, 2), (3, 4))), container=tuple, use_ordered_dict=True) == \ nifty_collections.OrderedDict([(2, ('meow', 1)), (4, (3,))]) # Sorting: assert get_equivalence_classes({1: 2, 3: 4, 'meow': 2}, sort_ordered_dict=True) == \ nifty_collections.OrderedDict([(2, set((1, 'meow'))), (4, set((3,)))]) assert get_equivalence_classes({1: 2, 3: 4, 'meow': 2}, sort_ordered_dict=lambda x: -x) == \ nifty_collections.OrderedDict([(4, set((3,))), (2, set((1, 'meow')))])