Open In App

Python | Convert byteString key:value pair of dictionary to String

Last Updated : 16 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a dictionary having key:value pairs as byteString, the task is to convert the key:value pair to string. 
Examples: 

Input: {b'EmplId': b'12345', b'Name': b'Paras', b'Company': b'Cyware' }
Output: {'EmplId': '12345', 'Name': 'Paras', 'Company': 'Cyware'}

Input: {b'Key1': b'Geeks', b'Key2': b'For', b'Key3': b'Geek' }
Output: {'Key1':'Geeks', 'Key2':'For', 'Key3':'Geek' }

  Method #1: By dictionary comprehension 

Python3




# Python Code to convert ByteString key:value
# pair of dictionary to String.
 
# Initialising dictionary
x = {b'EmplId': b'12345', b'Name': b'Paras', b'Company': b'Cyware'}
 
# Converting
x = { y.decode('ascii'): x.get(y).decode('ascii') for y in x.keys() }
 
# printing converted dictionary
print(x)


Output:

{'Name': 'Paras', 'EmplId': '12345', 'Company': 'Cyware'}

  Method #2: By iterating key and values 

Python3




# Python Code to convert ByteString key:value
# pair of dictionary to String.
 
# Initialising dictionary
x = {b'EmplId': b'12345', b'Name': b'Paras', b'Company': b'Cyware'}
 
# Initialising empty dictionary
y = {}
 
# Converting
for key, value in x.items():
    y[key.decode("utf-8")] = value.decode("utf-8")
 
# printing converted dictionary
print(y)


Output:

{'Company': 'Cyware', 'Name': 'Paras', 'EmplId': '12345'}

Approach#3: Using the ast module

This approach defines a function byteToStr which takes a dictionary with byte string keys and values as input and returns a dictionary with string keys and values. The function converts the input dictionary to a string, replaces all occurrences of b’ with ‘ and then uses ast.literal_eval to convert the resulting string back to a dictionary. This effectively removes the b prefix from byte strings and converts them to regular strings.

Algorithm

1. Import the ast module.
2. Use the literal_eval() method from the ast module to convert the input dictionary to a string.
3. Replace the byte string markers “b'” and “‘” with empty strings to convert the byte strings to strings.
4. Use the ast.literal_eval() method again to convert the string back to a dictionary.
5. Return the new dictionary.

Python3




import ast
 
def byteToStr(input_dict):
    str_dict = str(input_dict)
    str_dict = str_dict.replace("b'", "'").replace("'", "\"")
    return ast.literal_eval(str_dict)
 
input_dict = {b'EmplId': b'12345', b'Name': b'Paras', b'Company': b'Cyware'}
print(byteToStr(input_dict)) 


Output

{'EmplId': '12345', 'Name': 'Paras', 'Company': 'Cyware'}

Time complexity: O(n) where n is the number of key-value pairs in the input dictionary. 
Space complexity: O(n) since the input dictionary is converted to a string representation which takes up additional memory.

Approach#4: Using dict , map, lambda

The approach uses iterating through the key-value pairs of the input byte dictionary and decoding each byte key and value to string. Then, we can create a new dictionary using the decoded string keys and values. This can be done using dictionary comprehension or a for loop. In the given code, map() function is used to decode the byte key-value pairs and create a new dictionary.

Algorithm

1. Create an empty dictionary string_dict.
2. Iterate through each key-value pair of the input dictionary using the items() function.
3. For each key-value pair, decode the byte key and value to string using the decode() function.
4. Add the decoded key-value pair to the string_dict.
5. Return the string_dict.

Python3




def convert_byte_dict_to_string_dict(byte_dict):
    return dict(map(lambda item: (item[0].decode(), item[1].decode()), byte_dict.items()))
     
byte_dict = {b'EmplId': b'12345', b'Name': b'Paras', b'Company': b'Cyware' }
string_dict = convert_byte_dict_to_string_dict(byte_dict)
print(string_dict)


Output

{'EmplId': '12345', 'Name': 'Paras', 'Company': 'Cyware'}

Time Complexity: O(n), where n is the number of key-value pairs in the input byte dictionary. This is because the code iterates through each key-value pair once and performs constant-time operations on each pair.

Space Complexity: O(n), where n is the number of key-value pairs in the input byte dictionary. This is because the code creates a new dictionary of size n to store the decoded string key-value pairs. The space complexity can be reduced to O(1) if we modify the input byte dictionary in place to store the decoded string key-value pairs instead of creating a new dictionary. However, this may not be desirable if we want to preserve the original byte dictionary.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads