def iterate_flattened_separately(dictionary, manually_sorted_keys=None):
    """
    Recursively iterate over the items of a dictionary in a special order.

    First iterate over manually sorted keys and then over all items that are
    non-dictionary values (sorted by keys), then over the rest
    (sorted by keys), providing full dotted paths for every leaf.
    """
    manually_sorted_keys = manually_sorted_keys or []

    def get_order(key_and_value):
        key, value = key_and_value
        if key in manually_sorted_keys:
            return 0, manually_sorted_keys.index(key)
        elif not is_non_empty_dict(value):
            return 1, key
        else:
            return 2, key

    for key, value in sorted(dictionary.items(), key=get_order):
        if is_non_empty_dict(value):
            yield key, PATHCHANGE
            for k, val in iterate_flattened_separately(value, manually_sorted_keys):
                yield join_paths(key, k), val
        else:
            yield key, value

    Recursively iterate over the items of a dictionary in a special order.

    First iterate over manually sorted keys and then over all items that are
    non-dictionary values (sorted by keys), then over the rest
    (sorted by keys), providing full dotted paths for every leaf.
    
sacred/utils.py