Python 如何将字节类型转换为字典?

Python 如何将字节类型转换为字典?,python,string,dictionary,Python,String,Dictionary,我有一个字节类型的对象,如下所示: b"{'one': 1, 'two': 2}" 我需要使用python代码从中获取字典。我把它转换成字符串,然后转换成字典,如下所示 string = dictn.decode("utf-8") print(type(string)) >> <class 'str'> d = dict(toks.split(":") for toks in string.split(",") if toks) 您只需要ast.literal\u e

我有一个字节类型的对象,如下所示:

b"{'one': 1, 'two': 2}"
我需要使用python代码从中获取字典。我把它转换成字符串,然后转换成字典,如下所示

string = dictn.decode("utf-8")
print(type(string))
>> <class 'str'>
d = dict(toks.split(":") for toks in string.split(",") if toks)

您只需要
ast.literal\u eval
。没有比这更有趣的了。除非在字符串中特别使用非Python dict语法,否则没有理由乱用JSON

# python3
import ast
byte_str = b"{'one': 1, 'two': 2}"
dict_str = byte_str.decode("UTF-8")
mydata = ast.literal_eval(dict_str)
print(repr(mydata))

见答案。它还详细说明了
ast.literal\u eval
如何比
eval
更安全。您可以这样尝试:

import json
import ast

a= b"{'one': 1, 'two': 2}"
print(json.loads(a.decode("utf-8").replace("'",'"')))

print(ast.literal_eval(a.decode("utf-8")))
有模块的单据:

一,


2.

我认为要得到正确的口述还需要解码

a= b"{'one': 1, 'two': 2}"
ast.literal_eval(a.decode('utf-8'))
**Output:** {'one': 1, 'two': 2}
公认的答案是肯定的

a= b"{'one': 1, 'two': 2}"
ast.literal_eval(repr(a))
**output:**  b"{'one': 1, 'two': 2}"
在我的许多代码中,literal_eval并没有正确地实现这一点,因此我个人更喜欢使用json模块

import json
a= b"{'one': 1, 'two': 2}"
json.loads(a.decode('utf-8'))
**Output:** {'one': 1, 'two': 2}

您可以使用Base64库将字符串字典转换为字节,尽管您可以使用json库将字节结果转换为字典。尝试下面的示例代码

import base64
import json


input_dict = {'var1' : 0, 'var2' : 'some string', 'var1' : ['listitem1','listitem2',5]}

message = str(input_dict)
ascii_message = message.encode('ascii')
output_byte = base64.b64encode(ascii_message)

msg_bytes = base64.b64decode(output_byte)
ascii_msg = msg_bytes.decode('ascii')
# Json library convert stirng dictionary to real dictionary type.
# Double quotes is standard format for json
ascii_msg = ascii_msg.replace("'", "\"")
output_dict = json.loads(ascii_msg) # convert string dictionary to dict format

# Show the input and output
print("input_dict:", input_dict, type(input_dict))
print()
print("base64:", output_byte, type(output_byte))
print()
print("output_dict:", output_dict, type(output_dict))

无需创建自己的字典解析器。将字符串发送到您在此处发布的代码不会引发该异常。事实上,它几乎实现了您希望它做的事情(对处理引号字符时的一些错误进行模化,例如,您将得到一个像
“'two'”
”这样的键,而不是
“two”
)。同时,这个输入从何而来?使用Python dict的
repr
,并将其编码为UTF-8,这并不是存储稍后要加载的数据的好方法。最好使用JSON或Pickle之类的东西。的可能副本似乎需要额外解码。错误日志:raise VALUERROR('格式错误的节点或字符串:'+repr(节点))VALUERROR:格式错误的节点或字符串:b“{'one':1,'two':2}”与json一致。加载
import base64
import json


input_dict = {'var1' : 0, 'var2' : 'some string', 'var1' : ['listitem1','listitem2',5]}

message = str(input_dict)
ascii_message = message.encode('ascii')
output_byte = base64.b64encode(ascii_message)

msg_bytes = base64.b64decode(output_byte)
ascii_msg = msg_bytes.decode('ascii')
# Json library convert stirng dictionary to real dictionary type.
# Double quotes is standard format for json
ascii_msg = ascii_msg.replace("'", "\"")
output_dict = json.loads(ascii_msg) # convert string dictionary to dict format

# Show the input and output
print("input_dict:", input_dict, type(input_dict))
print()
print("base64:", output_byte, type(output_byte))
print()
print("output_dict:", output_dict, type(output_dict))