Open In App

Python | Convert key-value pair comma separated string into dictionary

Given a string, with different key-value pairs separated with commas, the task is to convert that string into the dictionary. These types of problems are common in web development where we fetch arguments from queries or get a response in the form of strings. Given below are a few methods to solve the task. 

Method #1: Using dictionary comprehension 






# Python3 code to demonstrate
# converting comma separated string
# into dictionary
 
# Initialising string
ini_string1 = 'name = akshat, course = btech, branch = computer'
 
# Printing initial string
print("Initial String", ini_string1)
 
# Converting string into dictionary
# using dict comprehension
res = dict(item.split("=") for item in ini_string1.split(", "))
 
# Printing resultant string
print("Resultant dictionary", str(res))

Output
Initial String name = akshat, course = btech, branch = computer
Resultant dictionary {'name ': ' akshat', 'course ': ' btech', 'branch ': ' computer'}

Time Complexity: O(n)
Auxiliary Space: O(n)



Method #2: Using Map and lambda 




# Python3 code to demonstrate
# converting comma separated string
# into dictionary
 
# Initialising string
ini_string1 = 'name = akshat, course = btech, branch = computer'
 
# Printing initial string
print("Initial String", ini_string1)
 
# Converting string into dictionary
# using map and lambda
res = dict(map(lambda x: x.split('='), ini_string1.split(', ')))
 
# Printing resultant string
print("Resultant dictionary", str(res))

Output
Initial String name = akshat, course = btech, branch = computer
Resultant dictionary {'name ': ' akshat', 'course ': ' btech', 'branch ': ' computer'}

Time Complexity: O(n)
Space Complexity: O(n)

  Method #3: Using eval() function 




# Python3 code to demonstrate
# converting comma separated string
# into dictionary
 
# Initialising string
ini_string1 = 'name ="akshat", course ="btech", branch ="computer"'
 
# Printing initial string
print("Initial String", ini_string1)
 
# Converting string into dictionary
# using eval
res = eval('dict('+ini_string1+')')
 
# Printing resultant string
print("Resultant dictionary", str(res))

Output
Initial String name ="akshat", course ="btech", branch ="computer"
Resultant dictionary {'name': 'akshat', 'course': 'btech', 'branch': 'computer'}

Time Complexity: O(n)
Space Complexity: O(n)

Method #4 : Using split() and index() methods




# Python3 code to demonstrate
# converting comma separated string
# into dictionary
 
# Initialising string
ini_string1 = 'name = akshat, course = btech, branch = computer'
 
# Printing initial string
print("Initial String", ini_string1)
 
# Converting string into dictionary
res = dict()
x = ini_string1.split(",")
for i in x:
    a = i[:i.index("=")]
    b = i[i.index("=")+1:]
    res[str(a)] = str(b)
# Printing resultant string
print("Resultant dictionary", str(res))

Output
Initial String name = akshat, course = btech, branch = computer
Resultant dictionary {'name ': ' akshat', ' course ': ' btech', ' branch ': ' computer'}

Time Complexity: O(n)
Space Complexity: O(n)

Method #5: Using Regular Expressions




import re
 
# Initialising string
ini_string1 = 'name = akshat, course = btech, branch = computer'
 
# Define regular expression pattern
pattern = r'(\w+)\s*=\s*(\w+)'
 
# Extract key-value pairs using regular expression
matches = re.findall(pattern, ini_string1)
 
# Convert list of matches to dictionary
res = {key: value for key, value in matches}
 
# Print resulting dictionary
print("Resultant dictionary:", res)

Output
('Resultant dictionary:', {'course': 'btech', 'name': 'akshat', 'branch': 'computer'})

Time complexity: (n), where n is the length of the input string. This is because it involves a single pass through the string to extract the key-value pairs using regular expressions, and then a dictionary comprehension to convert the list of matches to a dictionary.
Auxiliary space: O(m), where m is the number of key-value pairs in the input string. This is because it stores each key-value pair in a separate tuple in memory during the regular expression match, and then creates a dictionary with m key-value pairs.

Method 6: Using the re module 




import re
 
# Initializing string
ini_string1 = 'name = akshat, course = btech, branch = computer'
 
# Define regular expression pattern to match key-value pairs
pattern = r'(\S+)\s*=\s*(\S+)'
 
# Extract key-value pairs from the string using regular expression
key_value_pairs = re.findall(pattern, ini_string1)
 
# Create dictionary from the list of key-value pairs using dictionary comprehension
res = {key: value for key, value in key_value_pairs}
 
# Print the resultant dictionary
print("Resultant dictionary:", res)

Output
Resultant dictionary: {'name': 'akshat,', 'course': 'btech,', 'branch': 'computer'}

Time complexity:
The regular expression matching operation has a worst-case time complexity of O(nm), where n is the length of the input string and m is the length of the regular expression pattern. The iteration over the key-value pairs and dictionary comprehension operation has a time complexity of O(n), where n is the number of key-value pairs in the input string. Therefore, the overall time complexity of this approach is O(nm + n).
Auxiliary Space: O(n), where n is the number of key-value pairs in the input string.


Article Tags :