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
ini_string1 = 'name = akshat, course = btech, branch = computer'
print("Initial String", ini_string1)
res = dict(item.split("=") for item in ini_string1.split(", "))
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
ini_string1 = 'name = akshat, course = btech, branch = computer'
print("Initial String", ini_string1)
res = dict(map(lambda x: x.split('='), ini_string1.split(', ')))
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
ini_string1 = 'name ="akshat", course ="btech", branch ="computer"'
print("Initial String", ini_string1)
res = eval('dict('+ini_string1+')')
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
ini_string1 = 'name = akshat, course = btech, branch = computer'
print("Initial String", ini_string1)
res = dict()
x = ini_string1.split(",")
for i in x:
a = i[:i.index("=")]
b = i[i.index("=")+1:]
res[str(a)] = str(b)
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 the re module for regular expression operations Define a pattern to match each key-value pair in the string. In this case, the pattern is (\w+)\s*=\s*(\w+) , which matches any sequence of word characters (\w+) f ollowed by an equals sign (=) and any amount of whitespace (\s*) , followed by another sequence of word characters (\w+) . Use re.findall t o extract all matches of this pattern from the input string. Convert the list of matches into a dictionary using dictionary comprehension. Print the resulting dictionary.
Python
import re
ini_string1 = 'name = akshat, course = btech, branch = computer'
pattern = r'(\w+)\s*=\s*(\w+)'
matches = re.findall(pattern, ini_string1)
res = {key: value for key, value in matches}
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 the re module Initialize the input string ini_string1 Define a regular expression pattern to match the key-value pairs in the string. In this case, we will match any sequence of non-whitespace characters followed by an equal sign, followed by any sequence of non-whitespace characters. Use the re.findall() method to extract all the key-value pairs from the input string using the regular expression pattern. Iterate over the list of key-value pairs and split each pair using the split() method, which separates the key and value using the equal sign as the delimiter. Create a dictionary from the list of key-value pairs using dictionary comprehension. Print the resultant dictionary.
Python3
import re
ini_string1 = 'name = akshat, course = btech, branch = computer'
pattern = r'(\S+)\s*=\s*(\S+)'
key_value_pairs = re.findall(pattern, ini_string1)
res = {key: value for key, value in key_value_pairs}
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.
Last Updated :
16 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Add Your Comment
Please Login to comment...