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
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().
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.
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}
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With