예제 #1
0
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.items():
        if value not in new_dict:
            new_dict[value] = []
        new_dict[value].append(key)
    
    # Making into sets:
    for key, value in new_dict.copy().items():
        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, str)):
            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
예제 #2
0
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
예제 #3
0
 def sort(self, key=None, reverse=False):
     """
     Sort the items according to their keys, changing the order in-place.
     
     The optional `key` argument, (not to be confused with the dictionary
     keys,) will be passed to the `sorted` function as a key function.
     """
     key_function = comparison_tools.process_key_function_or_attribute_name(key)
     sorted_keys = sorted(self.keys(), key=key_function, reverse=reverse)
     for key_ in sorted_keys[1:]:
         self.move_to_end(key_)
예제 #4
0
 def sort(self, key=None, reverse=False):
     '''
     Sort the items according to their keys, changing the order in-place.
     
     The optional `key` argument, (not to be confused with the dictionary
     keys,) will be passed to the `sorted` function as a key function.
     '''
     key_function = \
                comparison_tools.process_key_function_or_attribute_name(key)
     sorted_keys = sorted(self.keys(), key=key_function, reverse=reverse)
     for key_ in sorted_keys[1:]:
         self.move_to_end(key_)
예제 #5
0
 def sort(self, key=None, reverse=False):
     '''
     Sort the items according to their keys, changing the order in-place.
     
     The optional `key` argument will be passed to the `sorted` function as
     a key function.
     '''
     # Inefficient implementation until someone cares.
     key_function = \
                comparison_tools.process_key_function_or_attribute_name(key)
     sorted_members = sorted(tuple(self), key=key_function, reverse=reverse)
     
     self.clear()
     self |= sorted_members
예제 #6
0
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
예제 #7
0
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.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 = dict((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.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