Sometimes, while working with Python strings, we can have problems in which we need to convert a string’s key-value pairs to the dictionary. This can have applications in which we are working with string data that needs to be converted. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using map() + split() + loop
The combination of above functionalities can be used to perform this task. In this, we perform the conversion of key-value pairs to the dictionary using a map, and splitting key-value pairs is done using split().
Python3
test_str = 'gfg:1, is:2, best:3'
print ( "The original string is : " + str (test_str))
res = []
for sub in test_str.split( ', ' ):
if ':' in sub:
res.append( map ( str .strip, sub.split( ':' , 1 )))
res = dict (res)
print ( "The converted dictionary is : " + str (res))
|
Output :
The original string is : gfg:1, is:2, best:3
The converted dictionary is : {'gfg': '1', 'is': '2', 'best': '3'}
Time complexity: O(n), where n is the length of the input string.
Auxiliary space: O(n), where n is the length of the input string.
Method #2 : Using dict() + generator expression + split() + map()
This is yet another way in which this problem can be solved. In this, we perform the task in a similar way as above but in 1 liner way using dict() and generator expression.
Python3
test_str = 'gfg:1, is:2, best:3'
print ( "The original string is : " + str (test_str))
res = dict ( map ( str .strip, sub.split( ':' , 1 ))
for sub in test_str.split( ', ' ) if ':' in sub)
print ( "The converted dictionary is : " + str (res))
|
Output :
The original string is : gfg:1, is:2, best:3
The converted dictionary is : {'gfg': '1', 'is': '2', 'best': '3'}
The Time and Space Complexity for all the methods are the same:
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #3: Using dict comprehension + split()
This is yet another way in which this problem can be solved. In this, we perform the task in a similar way as above but in 1 liner way using dict comprehension and split().
Python
test_str = 'gfg:1, is:2, best:3'
print ( "The original string is : " + str (test_str))
res = test_str.split( ', ' )
res = {i.split( ':' )[ 0 ]: i.split( ':' )[ 1 ] for i in res}
print ( "The converted dictionary is : " + str (res))
|
Output
The original string is : gfg:1, is:2, best:3
The converted dictionary is : {'is': '2', 'gfg': '1', 'best': '3'}
Method 4 : using regular expressions
Step-by-step explanation:
- Define a regular expression pattern that matches each key-value pair: (\w+):(\d+)
(\w+): match one or more word characters (letters, digits, or underscores), captured as a group
:: match a colon
(\d+): match one or more digits, captured as a group
- Use re.findall() to find all non-overlapping matches of the pattern in the input string.
- Use dict() to convert the list of matches into a dictionary.
Python3
import re
test_str = 'gfg:1, is:2, best:3'
print ( "The original string is : " + str (test_str))
pattern = r '(\w+):(\d+)'
res = dict (re.findall(pattern, test_str))
print ( "The converted dictionary is : " + str (res))
|
Output
The original string is : gfg:1, is:2, best:3
The converted dictionary is : {'gfg': '1', 'is': '2', 'best': '3'}
Time complexity: O(n), where n is the length of the input string.
Auxiliary space complexity is O(n + k).
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
28 Apr, 2023
Like Article
Save Article