Convert to a BadgerFish-style dict for addition to a dict suitable for
    addition to XML tree or for v1.0 to v0.0 conversion.
487162
def _convert_hbf_meta_val_for_xml(key, val):
    """"""
    if isinstance(val, list):
        return [_convert_hbf_meta_val_for_xml(key, i) for i in val]
    is_literal = True
    content = None
    if isinstance(val, dict):
        ret = val
        if '@href' in val:
            is_literal = False
        else:
            content = val.get('$')
            if isinstance(content, dict) and _contains_hbf_meta_keys(val):
                is_literal = False
    else:
        ret = {}
        content = val
    if is_literal:
        ret.setdefault('@xsi:type', 'nex:LiteralMeta')
        ret.setdefault('@property', key)
        if content is not None:
            ret.setdefault('@datatype', _python_instance_to_nexml_meta_datatype(content))
        if ret is not val:
            ret['$'] = content
    else:
        ret.setdefault('@xsi:type', 'nex:ResourceMeta')
        ret.setdefault('@rel', key)
    return ret
1005767
def to_dict(_dict, onts, mdb_safe=False):
    
    res = {}
    if isinstance(_dict, SamlBase):
        res["__class__"] = "%s&%s" % (_dict.c_namespace, _dict.c_tag)
        for key in _dict.keyswv():
            if key in IMP_SKIP:
                continue
            val = getattr(_dict, key)
            if key == "extension_elements":
                _eel = extension_elements_to_elements(val, onts)
                _val = [_eval(_v, onts, mdb_safe) for _v in _eel]
            elif key == "extension_attributes":
                if mdb_safe:
                    _val = dict([(k.replace(".", "__"), v) for k, v in
                                 val.items()])
                    #_val = {k.replace(".", "__"): v for k, v in val.items()}
                else:
                    _val = val
            else:
                _val = _eval(val, onts, mdb_safe)

            if _val:
                if mdb_safe:
                    key = key.replace(".", "__")
                res[key] = _val
    else:
        for key, val in _dict.items():
            _val = _eval(val, onts, mdb_safe)
            if _val:
                if mdb_safe and "." in key:
                    key = key.replace(".", "__")
                res[key] = _val
    return res
512052
def _merge(d, u):
    
    for k, v in u.items():
        # if we have a mapping, recursively merge the values
        if isinstance(v, collections.Mapping):
            d[k] = _merge(d.get(k, {}), v)

        # if d (the dict to merge into) is a dict, just add the
        # value to the dict.
        elif isinstance(d, collections.MutableMapping):
            d[k] = v

        # otherwise if d (the dict to merge into) is not a dict (e.g. when
        # recursing into it, `d.get(k, {})` may not be a dict), then do what
        # `update` does and prefer the new value.
        #
        # this means that something like `{'foo': 1}` when updated with
        # `{'foo': {'bar': 1}}` would have the original value (`1`) overwritten
        # and would become: `{'foo': {'bar': 1}}`
        else:
            d = {k: v}

    return d
706548
def to_dict(self, remove_nones=False):
        

        if remove_nones:
            return {k: v for k, v in self.to_dict().items() if v is not None}
        else:
            raise NotImplementedError()
445863
def dict_of_lists_add(dictionary, key, value):
    # type: (DictUpperBound, Any, Any) -> None
    
    list_objs = dictionary.get(key, list())
    list_objs.append(value)
    dictionary[key] = list_objs
773831
def dict_unicodeize(some_dict):
    """"""

    # some python 2/3 compat
    if isinstance(some_dict, ("".__class__, u"".__class__)):
        if sys.version_info >= (3, 0):
            return some_dict

        return some_dict.decode('utf-8')
    elif isinstance(some_dict, collections.Mapping):
        return dict(map(dict_unicodeize, iteritems(some_dict)))
    elif isinstance(some_dict, collections.Iterable):
        return type(some_dict)(map(dict_unicodeize, some_dict))

    return some_dict
181391
def _pylxd_model_to_dict(obj):
    ''''''
    marshalled = {}
    for key in obj.__attributes__.keys():
        if hasattr(obj, key):
            marshalled[key] = getattr(obj, key)
    return marshalled
1145557
def _xml_to_dict(xml):
    '''
    
    '''
    dicts = {}
    for item in xml:
        key = item.tag.lower()
        idx = 1
        while key in dicts:
            key += six.text_type(idx)
            idx += 1
        if item.text is None:
            dicts[key] = _xml_to_dict(item)
        else:
            dicts[key] = item.text

    return dicts
866850
def _xml_to_dict(xml_to_convert):
    

    logger.debug("Converting to Python dict this XML: " + str(xml_to_convert))
    return xmltodict.parse(xml_to_convert, attr_prefix='')
535199
def to_python(self, value):
        """"""
        if isinstance(value, str):
            return value
        elif isinstance(value, dict):
            try:
                value = value['url']
            except KeyError:
                raise ValidationError("dictionary must contain an 'url' element")

            if not isinstance(value, str):
                raise ValidationError("field's url element must be a string")

            return value
        elif not isinstance(value, None):
            raise ValidationError("field must be a string or a dict")
153656
def _clean_xmldict_single_dic(self, dictionary):
        
        for k, v in dictionary.items():
            if v is None:
                dictionary[k] = ''
1075016
def as_dict(self):
        """"""
        def conv(v):
            if isinstance(v, SerializableAttributesHolder):
                return v.as_dict()
            elif isinstance(v, list):
                return [conv(x) for x in v]
            elif isinstance(v, dict):
                return {x:conv(y) for (x,y) in v.items()}
            else:
                return v
        return {k.replace('_', '-'): conv(v) for (k, v) in self._attributes.items()}
446851
def node_to_dict(node):
    
    dic = dict(tag=striptag(node.tag))
    if node.attrib:
        dic['attrib'] = node.attrib
    if node.text is not None:
        dic['text'] = node.text
    if node.nodes:
        dic['nodes'] = [node_to_dict(n) for n in node]
    return dic
314363
def _encode_dict(self, obj):
        """"""

        self._increment_nested_level()

        buffer = []
        for key in obj:
            buffer.append(self._encode_key(key) + ':' + self._encode(obj[key]))

        self._decrement_nested_level()

        return '{'+ ','.join(buffer) + '}'
1355228
def xml2dict(root):
    
    output = {}
    if root.items():
        output.update(dict(root.items()))

    for element in root:
        if element:
            if len(element) == 1 or element[0].tag != element[1].tag:
                one_dict = xml2dict(element)
            else:
                one_dict = {ns(element[0].tag): xml2list(element)}

            if element.items():
                one_dict.update(dict(element.items()))
            output.update({ns(element.tag): one_dict})

        elif element.items():
            output.update({ns(element.tag): dict(element.items())})

        else:
            output.update({ns(element.tag): element.text})

    return output
1338656
def prefix_dict_keys(d: Dict[str, Any], prefix: str) -> Dict[str, Any]:
    
    result = {}  # type: Dict[str, Any]
    for k, v in d.items():
        result[prefix + k] = v
    return result
908516
def to_python(self, value):
        
        if not value:
            return {}
        elif isinstance(value, six.string_types):
            res = loads(value)
            assert isinstance(res, dict)
            return JSONDict(**res)
        else:
            return value