Saturday, December 28, 2024
Google search engine
HomeLanguagesPython | Convert key-value pair comma separated string into dictionary

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




# 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




# 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




# 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




# 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 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+) followed by an equals sign (=) and any amount of whitespace (\s*), followed by another sequence of word characters (\w+).
  • Use re.findall to 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
 
# 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 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
 
# 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.

RELATED ARTICLES

Most Popular

Recent Comments