简体   繁体   English

我如何将以字节编码的 python 字典转换为 UTF-8 字典

[英]How could I convert a python dictionary that is encoded in bytes, into a UTF-8 Dictionary

I have the following dictionary: pointsdict = {b'335139450613137430': b'1', b'704168692828864574': b'22'} where the first element is the user id and the second element is points.我有以下字典: pointsdict = {b'335139450613137430': b'1', b'704168692828864574': b'22'}其中第一个元素是用户 ID,第二个元素是点。 How could I change 335139450613137430's amount of points.我怎么能改变 335139450613137430 的点数。

I have tried我努力了

decoded = pointsdict.decode()
decoded[userid] = pointstoset
pointsdict = decoded.encode()

and have received AttributeError: 'dict' object has no attribute 'decode' on the first line.并收到AttributeError: 'dict' object has no attribute 'decode'在第一行。 How can I do this?我怎样才能做到这一点?

Thanks - Evan谢谢 - 埃文

Here is how you can store the decoded items into another dictionary:以下是如何将解码的项目存储到另一个字典中:

pointsdict = {b'335139450613137430': b'1', b'704168692828864574': b'22'}

decoded = {}

for key in pointsdict.keys():
    decoded[key.decode('ascii')] = pointsdict[key].decode('ascii')

print(decoded)

Output: Output:

{'335139450613137430': '1', '704168692828864574': '22'}



The code can be more compacted like this:代码可以像这样更紧凑:

decoded = {key.decode('ascii'):pointsdict[key].decode(ascii) for key in pointsdict.keys()}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM