Convert a flat list of key/values into an OrderedDict
359834
def fields_to_dict(fields, type_=OrderedDict):
    """"""
    fields_iterator = iter(fields)
    return type_(zip(fields_iterator, fields_iterator))
530790
def _get_normalized_columns(cls, list_):
        
        ret = []
        for row in list_:
            if len(row.keys()) > len(ret):
                ret = cls._ordered_keys(row)

        for row in list_:
            for key in row.keys():
                if key not in ret:
                    ret.append(key)
                    if not isinstance(row, OrderedDict):
                        ret.sort()
        return ret
804623
def todict(self):
        """"""
        return OrderedDict((name, self[i]) for i, name in enumerate(self._fields))
786990
def _sorted_keys_items(dobj):
    """"""
    keys = sorted(dobj.keys())
    for key in keys:
        yield key, dobj[key]
638040
def dict2orderedlist(dic, order_list, default='', **kwargs):
    
    result = []
    for key_order in order_list:
        value = get_element(dic, key_order, **kwargs)
        result.append(value if value is not None else default)
    return result
1333856
def __clean_dict(dictionary):
        
        key_dict = {}
        value_dict = {}
        final_list = []
        for key in dictionary.keys():
            key_dict[key] = "seq"

        for value in dictionary.values():
            value_dict[value] = "text"

        for (key1, value1), (key2, value2) in zip(key_dict.items(), value_dict.items()):
            final_list.append({value1: int(key1), value2: key2})

        return final_list
169186
def sort_recursive(data):
    

    newdict = {}

    for i in data.items():
        if type(i[1]) is dict:
            newdict[i[0]] = sort_recursive(i[1])
        else:
            newdict[i[0]] = i[1]

    return OrderedDict(sorted(newdict.items(), key=lambda item: (compare_type(type(item[1])), item[0])))
914217
def sort_dict_by_key(obj):
    
    sort_func = lambda x: x[0]
    return OrderedDict(sorted(obj.items(), key=sort_func))
738755
def ordered_dump(data, stream=None, Dumper=yaml.SafeDumper, **kwds):
    """"""
    class OrderedDumper(Dumper):
        pass

    def dict_representer(dumper, data):
        return dumper.represent_mapping(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, data.items())

    OrderedDumper.add_representer(OrderedDict, dict_representer)

    return yaml.dump(data, stream, OrderedDumper, **kwds)
965358
def flatten(data, parent_key='', sep='_'):
    
    items = []

    if isinstance(data, list):
        logger.debug('Flattening list {}'.format(data))
        list_keys = [str(i) for i in range(0, len(data))]
        items.extend(
            flatten(dict(zip(list_keys, data)), parent_key, sep=sep).items())

    elif isinstance(data, dict):
        logger.debug('Flattening dict {}'.format(data))

        for key, value in data.items():
            new_key = parent_key + sep + key if parent_key else key
            if isinstance(value, collections.MutableMapping):
                items.extend(flatten(value, new_key, sep=sep).items())
            else:
                if isinstance(value, list):
                    list_keys = [str(i) for i in range(0, len(value))]
                    items.extend(
                        flatten(
                            dict(zip(list_keys, value)), new_key, sep=sep).items())
                else:
                    items.append((new_key, value))
    else:
        logger.debug('Nothing to flatten with {}'.format(data))
        return data

    return collections.OrderedDict(items)
408547
def to_OrderedDict(self, include_null=True):
        
        if include_null:
            return OrderedDict(self.items())
        else:
            items = list()
            for c in self.__table__._columns:
                try:
                    items.append((c.name, self.__dict__[c.name]))
                except KeyError:
                    pass
            return OrderedDict(items)
574700
def flattened_nested_key_indices(nested_dict):
    
    outer_keys, inner_keys = collect_nested_keys(nested_dict)
    combined_keys = list(sorted(set(outer_keys + inner_keys)))
    return {k: i for (i, k) in enumerate(combined_keys)}
1260319
def deep_convert_dict(value):
    
    to_ret = value
    if isinstance(value, OrderedDict):
        to_ret = dict(value)

    try:
        for k, v in to_ret.items():
            to_ret[k] = deep_convert_dict(v)
    except AttributeError:
        pass

    return to_ret
405847
def recursive_asdict(d):
    """"""
    out = {}
    for k, v in asdict(d).iteritems():
        if hasattr(v, '__keylist__'):
            out[k] = recursive_asdict(v)
        elif isinstance(v, list):
            out[k] = []
            for item in v:
                if hasattr(item, '__keylist__'):
                    out[k].append(recursive_asdict(item))
                else:
                    out[k].append(item)
        else:
            out[k] = v
    return out
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
410469
def flatten_dict(dic, parent_key='', sep='.'):
    
    items = []
    for key, value in dic.items():
        new_key = parent_key + sep + key if parent_key else key
        if isinstance(value, collections.MutableMapping):
            items.extend(flatten_dict(value, new_key, sep=sep).items())
        elif isinstance(value, list):
            for idx, elt in enumerate(value):
                items.extend(
                    flatten_dict(elt, new_key + sep + str(idx), sep=sep).items()
                )
        else:
            items.append((new_key, value))
    return dict(items)
193261
def sort_dict(d, desc=True):

    

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