给定一个字典,如果唯一的类型是字符串,如何编码utf-8字典键值?例如,使用字典理解:

{k.encode("utf-8"): v.encode("utf-8") for k, v in mydict.iteritems()}


给定:mydict = {u'foo': u'bar', u'red': u'color', u'size': 12},对字典键值进行编码,使其变为mydict = {'foo': 'bar', 'red': 'color', 'size': 12}

最佳答案

使用条件:

{
    k.encode("utf-8") if isinstance(k, unicode) else k:
    v.encode("utf-8") if isinstance(v, unicode) else v
    for k, v in mydict.iteritems()
}


或辅助功能:

def conditional_encode(s, encoding='utf-8', errors='strict'):
    if isinstance(s, unicode):
        return s.encode(encoding, errors)
    return s

{conditional_encode(k): conditional_encode(v) for k, v in mydict.iteritems()}

关于python - 如果类型为字符串,则utf-8编码字典键值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47125269/

10-12 20:06