Answer a question

I have a bytes type object like this:

b"{'one': 1, 'two': 2}"

I need to get the dictionary from that using python code. I am converting it into string and then converting into dictionary as follows.

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

But I am getting the below error:

------> d = dict(toks.split(":") for toks in string.split(",") if toks)
TypeError: 'bytes' object is not callable

Answers

All you need is ast.literal_eval. Nothing fancier than that. No reason to mess with JSON unless you are specifically using non-Python dict syntax in your string.

# 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))

See answer here. It also details how ast.literal_eval is safer than eval.

Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐