python - 将键:值对从字节串转换为字符串的最佳方法是什么?
问题描述
可以说我有一个字典:
{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'}
解决方案
d = { b'Name': b'John', b'age': b'43' }
d = { x.decode('ascii'): d.get(x).decode('ascii') for x in d.keys() }
推荐阅读
- javascript - 如何在 Javascript 中返回具有特定条件的对象数组?
- css - 无论我出于某种原因尝试什么,都无法让 SCSS/CSS 在 React App 中呈现
- python - 类型错误:dayofweek() 缺少 2 个必需的位置参数:“days”和“yr”
- java - Apache httpclient:块编码消息正文的过早结束:预期关闭块
- jenkins - 詹金斯 v1.563 旧版
- linux - 需要知道 bash 脚本中 disown 命令的目的
- javascript - 在此处粘贴 dom 标记以进行缩放
- typescript - Vue 组件中缺少 this 的属性
- angular - “TypeError:control.registerOnChange 不是函数”动态更改归档表单 FormControl 到 FormArray
- node.js - 如何使用 child_process.exec(command[, options][, callback]) 在 Node.js 应用程序中编译带有一些用户输入的 ac 程序