简体   繁体   中英

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. How could I change 335139450613137430's amount of points.

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. 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:

{'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()}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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