Python Dictionary to Bytes and Bytes to Dictionary

Bytes to Dictionary

import ast

byte_str = b"{'one': 1, 'two': 2}"
dict_str = byte_str.decode("UTF-8")
my_data = ast.literal_eval(dict_str)

print(repr(my_data))
>>> {'one': 1, 'two': 2}

Dictionary to Bytes

import json
user_dict = {'name': 'dinesh', 'code': 'dr-01'}
user_encode_data = json.dumps(user_dict, indent=2).encode('utf-8')

print(user_encode_data)
>>> b'{\n  "name": "dinesh",\n  "code": "dr-01"\n}'

Reference

© Kimi Tsai all right reserved.            Updated : 2023-07-12 09:04:54

results matching ""

    No results matching ""

    results matching ""

      No results matching ""