如何将字节类型转换为字典? [英] How to convert bytes type to dictionary?

查看:68
本文介绍了如何将字节类型转换为字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字节类型的对象,像这样:

I have a bytes type object like this:

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

我需要使用python代码从字典中获取字典.我将其转换为字符串,然后按如下所示转换为字典.

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

推荐答案

您需要的只是 ast.literal_eval .没有比这更好的了.除非您在字符串中专门使用非Python dict语法,否则无需弄乱JSON.

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

此处中查看答案.它还详细说明了 ast.literal_eval eval 更安全.

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

这篇关于如何将字节类型转换为字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆