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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49184578/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:00:33  来源:igfitidea点击:

How to convert bytes type to dictionary?

pythonstringdictionary

提问by Harathi

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.

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

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

采纳答案by mattmc3

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.

您只需要ast.literal_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))

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

请参阅此处的答案。它还详细说明了如何ast.literal_evaleval.

回答by H S Rathore

I think a decode is also required to get a proper dict.

我认为还需要解码才能获得正确的字典。

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

The accepted answer yields

接受的答案产生

a= b"{'one': 1, 'two': 2}"
ast.literal_eval(repr(a))
**output:**  b"{'one': 1, 'two': 2}"

The literal_eval hasn't done that properly with many of my codes so I personally prefer to use json module for this

我的许多代码都没有正确使用literal_eval,所以我个人更喜欢为此使用json模块

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

回答by William Feirie

You could try like this:

你可以这样尝试:

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

There are the doc of module:

有模块的文档:

1.ast doc

1. ast 文档

2.json doc

2. json文档

回答by Saeed Zahedian Abroodi

You can use Base64 library to convert string dictionary to bytes, and although you can convert bytes result to a dictionary using json library. Try this below sample code.

您可以使用 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))

enter image description here

在此处输入图片说明