Interconversion between data is quite popular and this particular article discusses about how interconversion of dictionary into bytes and vice versa can be obtained. Let’s look at the method that can help us achieve this particular task.
Method : Using encode() + dumps() + decode() + loads() The encode and dumps function together performs the task of converting the dictionary to string and then to corresponding byte value. This can be interconverted using the decode and loads function which returns the string from bytes and converts that to the dictionary again.
Python3
# Python3 code to demonstrate working of # Interconversion between Dictionary and Bytes # Using encode() + dumps() + decode() + loads() import json # initializing dictionary test_dict = { 'Gfg' : 1 , 'is' : 2 , 'best' : 3 } # printing original dictionary print ("The original dictionary is : " + str (test_dict)) # using encode() + dumps() to convert to bytes res_bytes = json.dumps(test_dict).encode( 'utf-8' ) # printing type and binary dict print ("The type after conversion to bytes is : " + str ( type (res_bytes))) print ("The value after conversion to bytes is : " + str (res_bytes)) # using decode() + loads() to convert to dictionary res_dict = json.loads(res_bytes.decode( 'utf-8' )) # printing type and dict print ("The type after conversion to dict is : " + str ( type (res_dict))) print ("The value after conversion to dict is : " + str (res_dict)) |
The original dictionary is : {'Gfg': 1, 'best': 3, 'is': 2} The type after conversion to bytes is : <class 'bytes'> The value after conversion to bytes is : b'{"Gfg": 1, "best": 3, "is": 2}' The type after conversion to dict is : <class 'dict'> The value after conversion to dict is : {'Gfg': 1, 'best': 3, 'is': 2}
Method #2: using pickle module
Approach
The pickle module to convert a dictionary to bytes and vice versa. pickle is a built-in module in Python that provides functionality for serializing and de-serializing Python objects, including dictionaries.
Algorithm
1. Import the pickle module
2. Define the dictionary
3. Convert the dictionary to bytes using pickle.dumps()
4. Print the type and value of the bytes object
5. Convert the bytes object back to dictionary using pickle.loads()
6. Print the type and value of the dictionary object
Python3
import pickle # Define the dictionary my_dict = { 'Gfg' : 1 , 'best' : 3 , 'is' : 2 } # Convert dictionary to bytes using pickle.dumps() bytes_dict = pickle.dumps(my_dict) # Print the type and value of the bytes object print ( "Type of bytes object:" , type (bytes_dict)) print ( "Value of bytes object:" , bytes_dict) # Convert bytes object back to dictionary using pickle.loads() dict_obj = pickle.loads(bytes_dict) # Print the type and value of the dictionary object print ( "Type of dictionary object:" , type (dict_obj)) print ( "Value of dictionary object:" , dict_obj) |
Type of bytes object: <class 'bytes'> Value of bytes object: b'\x80\x03}q\x00(X\x03\x00\x00\x00Gfgq\x01K\x01X\x04\x00\x00\x00bestq\x02K\x03X\x02\x00\x00\x00isq\x03K\x02u.' Type of dictionary object: <class 'dict'> Value of dictionary object: {'Gfg': 1, 'best': 3, 'is': 2}
Time complexity: The time complexity of this approach is O(n), where n is the number of key-value pairs in the dictionary.
Auxiliary Space: The space complexity of this approach is O(n), where n is the number of key-value
Method 3 : using the JSON module in Python.
step-by-step approach
- Import the JSON module using import json.
- Define a Python dictionary my_dict with some key-value pairs.
- Convert the dictionary to a JSON string using the json.dumps() function. This function takes a Python object (in this case, the dictionary my_dict) and returns a JSON-encoded string.
- Store the resulting JSON string in the variable json_str.
- Print the type and value of the json_str variable using the print() function. The type() function returns the type of the variable (in this case, str), and the print() function displays the value of the variable in the console.
- Convert the JSON string back to a Python dictionary using the json.loads() function. This function takes a JSON-encoded string (in this case, json_str) and returns a Python object (in this case, a dictionary).
- Store the resulting dictionary in the variable dict_obj.
- Print the type and value of the dict_obj variable using the print() function, just like in step 5.
- The program is now complete and will exit.
Python3
import json # Define the dictionary my_dict = { 'Gfg' : 1 , 'best' : 3 , 'is' : 2 } # Convert dictionary to JSON string using json.dumps() json_str = json.dumps(my_dict) # Print the type and value of the JSON string print ( "Type of JSON string:" , type (json_str)) print ( "Value of JSON string:" , json_str) # Convert JSON string back to dictionary using json.loads() dict_obj = json.loads(json_str) # Print the type and value of the dictionary object print ( "Type of dictionary object:" , type (dict_obj)) print ( "Value of dictionary object:" , dict_obj) |
Type of JSON string: <class 'str'> Value of JSON string: {"Gfg": 1, "best": 3, "is": 2} Type of dictionary object: <class 'dict'> Value of dictionary object: {'Gfg': 1, 'best': 3, 'is': 2}
The time complexity of this method is O(n)
The auxiliary space required is O(n), where n is the size of the dictionary.
Method 4: using numpy:
Algorithm:
- Define a dictionary ‘my_dict’ with key-value pairs.
- Use pickle.dumps() method to convert the dictionary object to bytes object ‘bytes_dict’.
- Print the type and value of bytes object.
- Use pickle.loads() method to convert the bytes object back to dictionary object ‘dict_obj’.
- Print the type and value of the dictionary object.
Python3
import numpy as np # Define the dictionary my_dict = { 'Gfg' : 1 , 'best' : 3 , 'is' : 2 } # Convert dictionary to ndarray using np.array() arr = np.array( list (my_dict.items())) # Print the type and value of the ndarray object print ( "Type of ndarray object:" , type (arr)) print ( "Value of ndarray object:" , arr) # Convert ndarray object back to dictionary using dict() dict_obj = dict (arr) # Print the type and value of the dictionary object print ( "Type of dictionary object:" , type (dict_obj)) print ( "Value of dictionary object:" , dict_obj) #This code is contributed by Vinay Pinajala |
Output: Type of ndarray object: <class 'numpy.ndarray'> Value of ndarray object: [['Gfg' '1'] ['best' '3'] ['is' '2']] Type of dictionary object: <class 'dict'> Value of dictionary object: {'Gfg': '1', 'best': '3', 'is': '2'}
Time Complexity:
Creating a dictionary has O(n) time complexity, where n is the number of key-value pairs.
pickle.dumps() and pickle.loads() methods have O(n) time complexity, where n is the size of the object being converted.
Printing values has O(1) time complexity.
Therefore, the overall time complexity is O(n).
Space Complexity:
The space required for creating the dictionary is O(n), where n is the number of key-value pairs.
The space required for bytes object ‘bytes_dict’ and dictionary object ‘dict_obj’ is also O(n), where n is the size of the dictionary.
The space required for other variables and print statements is O(1).
Therefore, the overall space complexity is O(n).