我有一个字典,其中所有元素都是字节。如何获得返回字符串的字典?

问题描述 投票:0回答:4

示例-我有这样的字典:

{b'mykey': {b'inner_key': b'inner_value'}}

如何将其转换为字符串和值都是字符串的字典?

python dictionary bytestring
4个回答
1
投票
def decode_dict(d, encoding_used = 'utf-8'): return { k.decode(encoding_used) : (v.decode(encoding_used) if isinstance(v, bytes) else decode_dict(v, encoding_used)) for k, v in d.items() } new_dict = decode_dict({b'mykey': {b'inner_key': b'inner_value'}}) print(new_dict)
如果您的编码不是UTF-8,则需要在调用中使用第二个参数。     

0
投票
使用解码:

b'somestring'.decode('utf-8')


0
投票
[使用简单的字典,例如{b'inner_key': b'inner_value'},您可以执行以下操作:

for k, v in list(d.items()): d[k.decode('utf8')] = d.pop(k).decode('utf8')

这需要扩展到可能存在嵌套字典的更一般的情况。但是,它会就地修改字典,如果您不想创建另一个字典,这可能会很有用。    

0
投票
我最终做了

def _convert_bytes_dict(data): out = {} for key, val in data.items(): if isinstance(val, list): decoded_val = [_convert_bytes_dict(i) for i in val] elif not hasattr(val, "items") and not hasattr(val, "decode"): decoded_val = val elif not hasattr(val, "items"): decoded_val = val.decode("utf-8") else: decoded_val = _convert_bytes_dict(val) out[key.decode("utf-8")] = decoded_val return out

© www.soinside.com 2019 - 2024. All rights reserved.