将key:value对从字节字符串转换为字符串的最佳方法是什么?

时间:2019-01-17 14:09:45

标签: python dictionary data-structures

我们说我有一个字典:

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

将其转换为以下内容的最佳方法是什么

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

(考虑可以有任意数量的key:value对)

这就是我现在拥有的:

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'}

3 个答案:

答案 0 :(得分:2)

export class ProjectOperation extends TestFields {
  projectList: TestFields[];

  constructor(
    private _http: HttpClient,
    private _services: DeoService
  ) {
    super();
    // this.projectList = new TestFields()
  }

  getProjects(): TestFields[] {
    // below is the line where i am getting error 
    this._services.getProjects('/api/project/getProject').subscribe(res => {
      this.getProjects = res;
    }); // this is the area i am getting error
    return this.projectList;
  }
}

答案 1 :(得分:1)

尝试一下:

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

y = {}

for key, value in x.items():
    y[key.decode("utf-8")] = value.decode("utf-8")

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

答案 2 :(得分:0)

我现在无法测试,但是您应该能够将所有内容解码为新字典。您应该指定编码-我认为UTF-8是一个很好的默认设置。

enc = 'utf-8'
s = {k.decode(enc), v.decode(enc) for k, v in d.items()}