Turns a dictionary into a bencoded str with alphabetized keys
        e.g., {'spam': 'eggs', 'cow': 'moo'} --> d3:cow3:moo4:spam4:eggse
1911
def bencode(canonical):
    '''
        
    '''
    in_dict = dict(canonical)

    def encode_str(in_str):
        out_str = str(len(in_str)) + ':' + in_str
        return out_str

    def encode_int(in_int):
        out_str = str('i' + str(in_int) + 'e')
        return out_str

    def encode_list(in_list):
        out_str = 'l'
        for item in in_list:
            out_str += encode_item(item)
        else:
            out_str += 'e'
        return out_str

    def encode_dict(in_dict):
        out_str = 'd'
        keys = sorted(in_dict.keys())
        for key in keys:
            val = in_dict[key]
            out_str = out_str + encode_item(key) + encode_item(val)
        else:
            out_str += 'e'
        return out_str

    def encode_item(x):
        if isinstance(x, str):
            return encode_str(x)
        elif isinstance(x, int):
            return encode_int(x)
        elif isinstance(x, list):
            return encode_list(x)
        elif isinstance(x, dict):
            return encode_dict(x)

    return encode_item(in_dict)
1274622
def key_dict( from_dict ):
	
	new_dict = {}
	old2new = {}
	new2old = {}
	for key in from_dict:
		k = normalizeUnicode(key,'identifier')
		if k != key:
			i = ''
			while new_dict.has_key("%s%s" % (k,i) ):
				if not i:
					i = 1
				else:
					i += 1
			k = "%s%s" % (k,i)
			old2new[key] = k
			new2old[k] = key
		new_dict[k] = from_dict[key]
	return (new_dict.keys(), new_dict, old2new, new2old)
509804
def encode_dict(dynamizer, value):
    
    encoded_dict = {}
    for k, v in six.iteritems(value):
        encoded_type, encoded_value = dynamizer.raw_encode(v)
        encoded_dict[k] = {
            encoded_type: encoded_value,
        }
    return 'M', encoded_dict
1147292
def from_dict(self, d):
        
        for key in d:
            if key == 'data':
                for dkey in d['data']:
                    if dkey in self._encode_fields:
                        setattr(self, str(dkey), base64.b64decode(d['data'][dkey]))
                    else:
                        setattr(self, str(dkey), d['data'][dkey])
            else:
                setattr(self, str(key), d[key])
67173
def _to_str(dumped_val, encoding='utf-8', ordered=True):
    
    _dict = OrderedDict if ordered else dict
    if isinstance(dumped_val, dict):
        return OrderedDict((k, _to_str(v, encoding)) for k,v in dumped_val.items())
    elif isinstance(dumped_val, (list, tuple)):
        return [_to_str(v, encoding) for v in dumped_val]
    elif isinstance(dumped_val, bytes):
        try:
            d = dumped_val.decode('utf-8')
        except Exception:
            d = repr(dumped_val)
        return d
    else:
        return dumped_val
1252834
def str2dict(dotted_str, value=None, separator='.'):
    
    dict_ = {}
    parts = dotted_str.split(separator)
    d, prev = dict_, None
    for part in parts:
        prev = d
        d = d.setdefault(part, {})
    else:
        if value is not None:
            prev[part] = value
    return dict_
1216503
def _recursively_convert_unicode_to_str(input):
    
    if isinstance(input, dict):
        return {_recursively_convert_unicode_to_str(key): _recursively_convert_unicode_to_str(value) for key, value in input.items()}
    elif isinstance(input, list):
        return [_recursively_convert_unicode_to_str(element) for element in input]
    elif not PYTHON_3 and isinstance(input, unicode):
        return input.encode('utf-8')
    else:
        return input
444799
def _encode(self):
        """"""
        obj = {k: v for k, v in self.__dict__.items()
               if not k.startswith('_') and type(v) in SAFE_TYPES}
        obj.update({k: v._encode() for k, v in self.__dict__.items()
                   if isinstance(v, Ent)})
        return obj
29925
def _dict_to_bson(doc, check_keys, opts, top_level=True):
    """"""
    if _raw_document_class(doc):
        return doc.raw
    try:
        elements = []
        if top_level and "_id" in doc:
            elements.append(_name_value_to_bson(b"_id\x00", doc["_id"],
                                                check_keys, opts))
        for (key, value) in iteritems(doc):
            if not top_level or key != "_id":
                elements.append(_element_to_bson(key, value,
                                                 check_keys, opts))
    except AttributeError:
        raise TypeError("encoder expected a mapping type but got: %r" % (doc,))

    encoded = b"".join(elements)
    return _PACK_INT(len(encoded) + 5) + encoded + b"\x00"
1007820
def prepare_for_json_encoding(obj):
    
    obj_type = type(obj)
    if obj_type == list or obj_type == tuple:
        return [prepare_for_json_encoding(item) for item in obj]
    if obj_type == dict:
        # alphabetizing keys lets us compare attributes for equality across runs
        return OrderedDict(
            (prepare_for_json_encoding(k),
             prepare_for_json_encoding(obj[k])) for k in sorted(obj.keys())
        )
    if obj_type == six.binary_type:
        return smart_unicode_decode(obj)
    if obj_type == bool or obj is None or obj_type == six.text_type or isinstance(obj, numbers.Number):
        return obj
    if obj_type == PSLiteral:
        # special case because pdfminer.six currently adds extra quotes to PSLiteral.__repr__
        return u"/%s" % obj.name
    return six.text_type(obj)
1216598
def dict_to_unicode(raw_dict):
    
    decoded = {}
    for key, value in raw_dict.items():
        decoded[to_unicode(key)] = map(
            to_unicode, value)
    return decoded
614254
def str2dict_keys(str_in):
    '''
    
    '''
    tmp_dict = str2dict(str_in)
    if tmp_dict is None:
        return None
    return sorted([k for k in tmp_dict])
1140266
def _decode_embedded_dict(src):
    '''
    
    '''
    output = {}
    for key, val in six.iteritems(src):
        if isinstance(val, dict):
            val = _decode_embedded_dict(val)
        elif isinstance(val, list):
            val = _decode_embedded_list(val)  # pylint: disable=redefined-variable-type
        elif isinstance(val, bytes):
            try:
                val = val.decode()
            except UnicodeError:
                pass
        if isinstance(key, bytes):
            try:
                key = key.decode()
            except UnicodeError:
                pass
        output[key] = val
    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
4237
def str2dict_values(str_in):
    '''
    
    '''
    tmp_dict = str2dict(str_in)
    if tmp_dict is None:
        return None
    return [tmp_dict[key] for key in sorted(k for k in tmp_dict)]
547301
def decode_dict(data):
    
    if six.PY3:
        return data
    rv = {}
    for key, value in iteritems(data):
        if isinstance(key, text_type):
            key = key.encode('utf-8')

        if isinstance(value, text_type):
            value = value.encode('utf-8')
        elif isinstance(value, list):
            value = _decode_list(value)
        # no need to recurse into dict, json library will do that
        rv[key] = value
    return rv
261718
def _to_key(d):
        """"""
        as_str = json.dumps(d, sort_keys=True)
        return as_str.replace('"{{', '{{').replace('}}"', '}}')