Helper function to extract formatted ordering from dict.
557164
def _get_ordering(son):
    
    def fmt(field, direction):
        return '{0}{1}'.format({-1: '-', 1: '+'}[direction], field)

    if '$orderby' in son:
        return ', '.join(fmt(f, d) for f, d in son['$orderby'].items())
193261
def sort_dict(d, desc=True):

    

    sort = sorted(d.items(), key=lambda x: x[1], reverse=desc)
    return OrderedDict(sort)
1102740
def keys(self):
        """"""

        keys = OrderedDict()

        def order_key(_):
            (k, v) = _
            cache_key = getattr(type(self), k)
            return cache_key.order

        items = [(k, getattr(type(self), k)) for k
            in dir(type(self))
        ]
        items = [(k, v) for (k, v)
            in items
            if isinstance(v, Key)
        ]

        for k, v in sorted(items, key=order_key):
            keys[k] = getattr(self, k)
        return keys
930574
def clean_dict(d):
    

    if not isinstance(d, (dict, list)):
        return d
    if isinstance(d, list):
        return [v for v in (clean_dict(v) for v in d) if v]
    return OrderedDict(
        [(k, v) for k, v in ((k, clean_dict(v)) for k, v in list(d.items())) if v]
    )
211053
def sort_def_dict(def_dict: Dict[str, List[str]]) -> Dict[str, List[str]]:
    """"""
    for _, dd_list in def_dict.items():
        dd_list.sort()
    return def_dict
195647
def _ordered_keys(dict_):
        
        return isinstance(dict_, OrderedDict) and dict_.keys() or \
               dict_ and sorted(dict_.keys()) or []
578166
def get_ordering(self):
        """"""
        if self.sorting_field:
            return [self.sorting_field]
        prefix = self.get_prefix()
        fields = self.get_ordering_with_prefix()
        if self.prefix:
            fields = [f.replace(prefix, "", 1) for f in fields]
        return [
            f
            for f in fields
            if f.lstrip("-") in self.get_ordering_fields_lookups()
        ]
858620
def get_valid_format_order(cls, format_target, format_order=None):
        
        format_order = format_order or cls.parse_format_order(format_target)
        cls.validate_no_token_duplicates(format_order)
        format_target = cls.remove_tokens(format_target, format_order)
        format_target = cls.remove_static_text(format_target)
        cls.validate_separator_characters(format_target)
        cls.validate_matched_parenthesis(format_target)
        return format_order
428720
def order_by_t(func):
    
    return Transformation(
        'order_by({0})'.format(name(func)),
        lambda sequence: sorted(sequence, key=func),
        None
    )
87426
def sort_dict(unsorted_dict):
    
    sorted_dict = OrderedDict()
    # sort items before inserting them into a dict
    for key, value in sorted(unsorted_dict.items(), key=itemgetter(0)):
        sorted_dict[key] = value
    return sorted_dict
120783
def dict_itemstr_list(dict_, **dictkw):
    
    """
    import utool as ut

    explicit = dictkw.get('explicit', False)
    dictkw['explicit'] = _rectify_countdown_or_bool(explicit)

    dosort = dictkw.get('sorted_', None)
    if dosort is None:
        dosort = True

    if dosort and not isinstance(dict_, collections.OrderedDict):
        key_order = dictkw.get('key_order', None)
        def iteritems(d):
            if key_order is None:
                # specify order explicilty
                try:
                    return iter(sorted(six.iteritems(d)))
                except TypeError:
                    # catches case where keys are of different types
                    return six.iteritems(d)
            else:
                # Enforce specific key order
                # TODO: depricate and just use ordered dicts
                unordered_keys = list(d.keys())
                other_keys = sorted(list(set(unordered_keys) - set(key_order)))
                keys = key_order + other_keys
                return ((key, d[key]) for key in keys)
    else:
        iteritems = six.iteritems

    _valstr = _make_valstr(**dictkw)

    precision = dictkw.get('precision', None)
    kvsep = dictkw.get('kvsep', ': ')
    if explicit:
        kvsep = '='

    def make_item_str(key, val):
        if explicit or dictkw.get('strkeys', False):
            key_str = six.text_type(key)
        else:
            key_str = repr2(key, precision=precision)

        prefix = key_str + kvsep
        val_str = _valstr(val)

        # FIXME: get indentation right
        if util_type.HAVE_NUMPY and isinstance(val, np.ndarray):
            item_str = hz_str(prefix, val_str)
        else:
            # padded_indent = ' ' * min(len(indent_), len(prefix))
            # val_str = val_str.replace('\n', '\n' + padded_indent)
            item_str = prefix + val_str
        return item_str

    itemstr_list = [make_item_str(key, val)
                    for (key, val) in iteritems(dict_)]

    reverse = False
    key_order_metric = dictkw.get('key_order_metric', None)
    if key_order_metric is not None:
        if key_order_metric.startswith('-'):
            key_order_metric = key_order_metric[1:]
            reverse = True

    if key_order_metric == 'strlen':
        metric_list = [len(itemstr) for itemstr in itemstr_list]
        itemstr_list = ut.sortedby(itemstr_list, metric_list, reverse=reverse)
    elif key_order_metric == 'val':
        metric_list = [val for (key, val) in iteritems(dict_)]
        itemstr_list = ut.sortedby(itemstr_list, metric_list, reverse=reverse)

    maxlen = dictkw.get('maxlen', None)
    if maxlen is not None and len(itemstr_list) > maxlen:
        itemstr_list = itemstr_list[0:maxlen]
    return itemstr_list
447680
def dumps(self, indent=1):
        

        str_keys_dict = OrderedDict({str(k): v for k, v in self.items()})
        for k, v in str_keys_dict.items():
            if isinstance(v, dict):
                str_keys_dict[k] = OrderedDict({str(k1): v1 for k1, v1 in v.items()})
                for k1, v1 in str_keys_dict[k].items():
                    if isinstance(v1, dict):
                        str_keys_dict[k][k1] = OrderedDict({str(k2): v2 for k2, v2 in v1.items()})
        return json.dumps(str_keys_dict, indent=indent)
153278
def str_dict(some_dict):
    """"""
    return {str(k): str(v) for k, v in some_dict.items()}
1124248
def getStyleDict(self):
        '''
            
        '''

        # TODO: This method is not used and does not appear in any tests.

        styleStr = (self.getAttribute('style') or '').strip()
        styles = styleStr.split(';') # Won't work for strings containing semicolon..
        styleDict = OrderedDict()
        for item in styles:
            try:
                splitIdx = item.index(':')
                name = item[:splitIdx].strip().lower()
                value = item[splitIdx+1:].strip()
                styleDict[name] = value
            except:
                continue

        return styleDict
1354047
def get_ordering(self):
        """"""
        _, ordering = self.token_next_by(t=T.Keyword.Order)
        return ordering.normalized if ordering else None
561886
def order_chunks(self, chunks):
        '''
        
        '''
        cap = 1
        for chunk in chunks:
            if 'order' in chunk:
                if not isinstance(chunk['order'], int):
                    continue

                chunk_order = chunk['order']
                if chunk_order > cap - 1 and chunk_order > 0:
                    cap = chunk_order + 100
        for chunk in chunks:
            if 'order' not in chunk:
                chunk['order'] = cap
                continue

            if not isinstance(chunk['order'], (int, float)):
                if chunk['order'] == 'last':
                    chunk['order'] = cap + 1000000
                elif chunk['order'] == 'first':
                    chunk['order'] = 0
                else:
                    chunk['order'] = cap
            if 'name_order' in chunk:
                chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
            if chunk['order'] < 0:
                chunk['order'] = cap + 1000000 + chunk['order']
            chunk['name'] = salt.utils.data.decode(chunk['name'])
        chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
        return chunks
114807
def get_order(self):
        
        return [dict(reverse=r[0], key=r[1]) for r in self.get_model()]