Friday, December 27, 2024
Google search engine
HomeLanguagesPython – Construct dictionary Key-Value pairs separated by delimiter

Python – Construct dictionary Key-Value pairs separated by delimiter

Given a String with key-value pairs separated by delim, construct a dictionary.

Input : test_str = ‘gfg#3, is#9, best#10’, delim = ‘#’ 
Output : {‘gfg’: ‘3’, ‘is’: ‘9’, ‘best’: ’10’} 
Explanation : gfg paired with 3, as separated with # delim.

Input : test_str = ‘gfg.10’, delim = ‘.’ 
Output : {‘gfg’: ’10’} 
Explanation : gfg paired with 10, as separated with . delim. 

Method #1 : Using split() + loop

In this, we perform a split on comma, to get key-value pairs, and again a split on custom delim to get key-value pairs separated. Then assigned to dictionary using loop.

Step-by-step approach :

  • Initializes a delimiter delim with the value “$”.
  • Splits the string test_str using the split() function with the argument ‘, ‘ to create a list of string elements. This list is stored in the variable dicts.
  • Initializes an empty dictionary res.
  • Starts a for loop with sub-iterating over each element of dicts.
    • Within the for loop, the string sub is split again using the split() function with the argument delim to create a list of two string elements.
    • The first element of the list (i.e. the key) is used as the key of the dictionary res and the second element of the list (i.e. the value) is used as the value of the dictionary res.
    • The key-value pair is added to the dictionary res.
  • After the for loop, the program prints the constructed dictionary res using the print() function.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Construct dictionary Key-Value pairs separated by delim
# Using split() + loop
 
# initializing strings
test_str = 'gfg$3, is$9, best$10'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing delim
delim = "$"
 
# split by comma for getting different dict values
dicts = test_str.split(', ')
 
res = dict()
for sub in dicts:
 
    # 2nd split for forming Key-Values for dictionary
    res[sub.split(delim)[0]]  = sub.split(delim)[1]
 
# printing result
print("The constructed dictionary : " + str(res))


Output

The original string is : gfg$3, is$9, best$10
The constructed dictionary : {'gfg': '3', 'is': '9', 'best': '10'}

Time complexity: O(n).
Auxiliary space: O(n).

Method #2 : Using dictionary comprehension + split()

Similar to above method, just the difference being that dictionary comprehension is used for performing task of dictionary construction.

Python3




# Python3 code to demonstrate working of
# Construct dictionary Key-Value pairs separated by delim
# Using split() + dictionary comprehension
 
# initializing strings
test_str = 'gfg$3, is$9, best$10'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing delim
delim = "$"
 
# split by comma for getting different dict values
dicts = test_str.split(', ')
 
# dictionary comprehension to form dictionary
res = {sub.split(delim)[0] : sub.split(delim)[1] for sub in dicts}
 
# printing result
print("The constructed dictionary : " + str(res))


Output

The original string is : gfg$3, is$9, best$10
The constructed dictionary : {'gfg': '3', 'is': '9', 'best': '10'}

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

Method 3: Using Regular Expressions

Regular expressions can be used to extract the key-value pairs from the string using a pattern that matches the delimiters and the keys and values. 

Python3




import re
 
test_str = 'gfg$3, is$9, best$10'
delim = "\$|, "  # pattern for matching delimiter
 
pattern = f"([^\{delim}]+){delim}([^\{delim}]+)"
matches = re.findall(pattern, test_str)
 
res = {key: value for key, value in matches}
 
print("The constructed dictionary : " + str(res))


Output

The constructed dictionary : {'gfg': '', '': 'best'}

Time complexity: O(n), where n is the length of the input string.
Auxiliary space: O(m), where m is the number of key-value pairs in the dictionary.

Method #4: Using str.partition()

Split the string into substrings based on the first occurrence of the delimiter and use str.partition() method to extract the key-value pairs.

Python3




test_str = 'gfg$3, is$9, best$10'
 
res = {}
 
for pair in test_str.split(', '):
    key, _, value = pair.partition('$')
    res[key] = int(value)
 
print("The constructed dictionary : " + str(res))


Output

The constructed dictionary : {'gfg': 3, 'is': 9, 'best': 10}

Time complexity: O(n), where n is the length of the input string.
Auxiliary space: O(n), because we are creating a dictionary with n/2 key-value pairs, and each key and value is a string of length at most n.

Method #5: Using zip() and list comprehension

This method involves using the zip() function to create a tuple of keys and values, and then using a list comprehension to construct the dictionary.

Step-by-step approach:

  • Initialize the string and delimiter
  • Split the string by comma and space to get a list of sub-strings
  • Use zip() to create a tuple of keys and values
  • Construct the dictionary using the tuple of keys and values
  • Print the resulting dictionary

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Construct dictionary Key-Value pairs separated by delim
# Using zip() and list comprehension
 
# initializing strings
test_str = 'gfg$3, is$9, best$10'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing delim
delim = "$"
 
# split by comma for getting different dict values
sub_strings = test_str.split(', ')
 
# use zip() to create tuple of keys and values
key_value_pairs = [(s.split(delim)[0], s.split(delim)[1]) for s in sub_strings]
 
# construct the dictionary
res = dict(key_value_pairs)
 
# printing result
print("The constructed dictionary : " + str(res))


Output

The original string is : gfg$3, is$9, best$10
The constructed dictionary : {'gfg': '3', 'is': '9', 'best': '10'}

Time complexity: O(n), where n is the length of the input string.
 Auxiliary space: O(n) as well, as we create a list of sub-strings and a list of tuples of keys and values.

Method #7: Using re.findall() and dict()

Here’s another approach to construct a dictionary with key-value pairs separated by a delimiter in Python using regular expressions:

step-by-step approach for the program:

  1. Import the re module.
  2. Initialize the input string test_str with the given value ‘gfg$3, is$9, best$10’.
  3. Initialize the delimiter delim with the value ‘\$’.
  4. Use the re.findall() function to extract all key-value pairs from the input string. The function takes two arguments: a regular expression pattern and a string to search. The pattern we use is r'([^,]+)’+delim+r'([^,]+)’, which matches any sequence of characters that are not commas (i.e., [^,]+) before and after the delimiter. The resulting key-value pairs are returned as a list of tuples.
  5. Store the resulting list of tuples in the variable pairs.
  6. Use the dict() constructor to construct a dictionary from the list of tuples in pairs. The constructor takes a list of key-value pairs as an argument, where each key-value pair is represented as a tuple.
  7. Store the resulting dictionary in the variable res.
  8. Print the resulting dictionary using the print() function.
  9. End of the program.

Python3




import re
 
# initializing input string
test_str = 'gfg$3, is$9, best$10'
 
# initializing delimiter
delim = "\$"
 
# using re.findall() to extract key-value pairs
pairs = re.findall(r'([^,]+)'+delim+r'([^,]+)', test_str)
 
# constructing the dictionary
res = dict(pairs)
 
# printing result
print("The constructed dictionary : " + str(res))


Output

The constructed dictionary : {'gfg': '3', ' is': '9', ' best': '10'}

The time complexity of this program depends on the efficiency of the regular expression engine used by Python’s re module. In general, the time complexity of re.findall() is O(n), where n is the length of the input string. Therefore, the time complexity of this program is O(n).

The auxiliary space of this program depends on the size of the resulting dictionary. The re.findall() method returns a list of tuples, which takes O(k) space, where k is the number of key-value pairs in the input string. The dict() constructor creates a dictionary from this list, which takes O(k) space as well. Therefore, the space complexity of this program is O(k).

RELATED ARTICLES

Most Popular

Recent Comments