Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert bytes type to dictionary?

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 
like image 539
Harathi Avatar asked Mar 09 '18 00:03

Harathi


People also ask

How do you convert a key to a dictionary?

Method #1 : Using map() + split() + loop In this, we perform the conversion of key-value pair to dictionary using map and splitting key-value pairs is done using split().

Can you convert a List into a dictionary?

To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements. Finally, typecase the list to dict type.


2 Answers

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

import json a= b"{'one': 1, 'two': 2}" json.loads(a.decode('utf-8')) **Output:** {'one': 1, 'two': 2} 
like image 159
H S Rathore Avatar answered Sep 21 '22 19:09

H S Rathore


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.

like image 36
mattmc3 Avatar answered Sep 18 '22 19:09

mattmc3