首页 > 解决方案 > 将键:值对从字节串转换为字符串的最佳方法是什么?

问题描述

可以说我有一个字典:

{b'Name': b'John', b'age': b'43'}

将其转换为:

{'Name': 'John', 'age': '43'}

(考虑到可以有任意数量的键:值对)

这就是我现在所拥有的:

new_d = dict()
old_d = {b'Name': b'John', b'age': b'43'}

for item in old_d:
    print(item, old_d[item])
    new_d[item.decode('ascii')] = old_d[item].decode('ascii')
    print(new_d)

输出:

{'Name': 'John', 'age': '43'}

标签: pythondictionarydata-structures

解决方案


d = { b'Name': b'John', b'age': b'43' }
d = { x.decode('ascii'): d.get(x).decode('ascii') for x in d.keys() }

推荐阅读