'Convert a MongoDB-compatible type to a Python type.'

def to_python(self, value):

    if isinstance(value, six.string_types):
        return value
    if hasattr(value, 'to_python'):
        return value.to_python()
    is_list = False
    if (not hasattr(value, 'items')):
        try:
            is_list = True
            value = {k: v for (k, v) in enumerate(value)}
        except TypeError:
            return value
    if self.field:
        self.field._auto_dereference = self._auto_dereference
        value_dict = {key: self.field.to_python(item) for (key, item) in value.items()}
    else:
        Document = _import_class('Document')
        value_dict = {}
        for (k, v) in value.items():
            if isinstance(v, Document):
                if (v.pk is None):
                    self.error('You    can    only    reference    documents    once    they    have    been    saved    to    the    database')
                collection = v._get_collection_name()
                value_dict[k] = DBRef(collection, v.pk)
            elif hasattr(v, 'to_python'):
                value_dict[k] = v.to_python()
            else:
                value_dict[k] = self.to_python(v)
    if is_list:
        return [v for (_, v) in sorted(value_dict.items(), key=operator.itemgetter(0))]
    return value_dict
