Python - Convert key-value String to dictionary
Last Updated :
28 Apr, 2023
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
# Python3 code to demonstrate working of
# Convert key-value String to dictionary
# Using map() + split() + loop
# initializing string
test_str = 'gfg:1, is:2, best:3'
# printing original string
print("The original string is : " + str(test_str))
# Convert key-value String to dictionary
# Using map() + split() + loop
res = []
for sub in test_str.split(', '):
if ':' in sub:
res.append(map(str.strip, sub.split(':', 1)))
res = dict(res)
# printing result
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
# Python3 code to demonstrate working of
# Convert key-value String to dictionary
# Using dict() + generator expression + split() + map()
# initializing string
test_str = 'gfg:1, is:2, best:3'
# printing original string
print("The original string is : " + str(test_str))
# Convert key-value String to dictionary
# Using dict() + generator expression + split() + map()
res = dict(map(str.strip, sub.split(':', 1))
for sub in test_str.split(', ') if ':' in sub)
# printing result
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
# Python3 code to demonstrate working of
# Convert key-value String to dictionary
# Using dict comprehension + split()
# initializing string
test_str = 'gfg:1, is:2, best:3'
# printing original string
print("The original string is : " + str(test_str))
# Convert key-value String to dictionary
# Using map() + split() + loop
res = test_str.split(', ')
res = {i.split(':')[0]: i.split(':')[1] for i in res}
# printing result
print("The converted dictionary is : " + str(res))
OutputThe 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
# initializing string
test_str = 'gfg:1, is:2, best:3'
# printing original string
print("The original string is : " + str(test_str))
# Convert key-value String to dictionary
# Using regular expressions
pattern = r'(\w+):(\d+)'
res = dict(re.findall(pattern, test_str))
# printing result
print("The converted dictionary is : " + str(res))
OutputThe 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).
Similar Reads
Python - Convert String List to Key-Value List dictionary
Given a string, convert it to key-value list dictionary, with key as 1st word and rest words as value list. Input : test_list = ["gfg is best for geeks", "CS is best subject"] Output : {'gfg': ['is', 'best', 'for', 'geeks'], 'CS': ['is', 'best', 'subject']} Explanation : 1st elements are paired with
8 min read
Convert Dictionary values to Strings
In Python, dictionaries store key-value pairs, where values can be of any data type. Sometimes, we need to convert all the values of a dictionary into strings. For example, given the dictionary {'a': 1, 'b': 2.5, 'c': True}, we might want to convert the values 1, 2.5, and True to their string repres
3 min read
Python - Convert dictionary items to values
Sometimes, while working with Python dictionary, we can have a problem in which we need to convert all the items of dictionary to a separate value dictionary. This problem can occur in applications in which we receive dictionary in which both keys and values need to be mapped as separate values. Let
3 min read
Convert byte string Key:Value Pair of Dictionary to String - Python
In Python, dictionary keys and values are often stored as byte strings when working with binary data or certain encoding formats, we may need to convert the byte strings into regular strings. For example, given a dictionary {b'key1': b'value1', b'key2': b'value2'}, we might want to convert it to {'k
3 min read
Convert Dictionary to String List in Python
The task of converting a dictionary to a string list in Python involves transforming the key-value pairs of the dictionary into a formatted string and storing those strings in a list. For example, consider a dictionary d = {1: 'Mercedes', 2: 'Audi', 3: 'Porsche', 4: 'Lambo'}. Converting this to a st
3 min read
Python - Concatenate Dictionary string values
The task of concatenating string values in a Python dictionary involves combining the values associated with the same key across multiple dictionaries. This operation allows us to merge string data in an efficient manner, especially when dealing with large datasets .For example, given two dictionari
4 min read
Python - Convert key-values list to flat dictionary
We are given a list that contains tuples with the pairs of key and values we need to convert that list into a flat dictionary. For example a = [("name", "Ak"), ("age", 25), ("city", "NYC")] is a list we need to convert it to dictionary so that output should be a flat dictionary {'name': 'Ak', 'age':
3 min read
Python Convert Dictionary to List of Values
Python has different types of built-in data structures to manage your data. A list is a collection of ordered items, whereas a dictionary is a key-value pair data. Both of them are unique in their own way. In this article, the dictionary is converted into a list of values in Python using various con
3 min read
Convert String Dictionary to Dictionary in Python
The goal here is to convert a string that represents a dictionary into an actual Python dictionary object. For example, you might have a string like "{'a': 1, 'b': 2}" and want to convert it into the Python dictionary {'a': 1, 'b': 2}. Let's understand the different methods to do this efficiently.Us
2 min read
Python - Convert Strings to Uppercase in Dictionary Value Lists
In Python, sometimes a dictionary contains lists as its values, and we want to convert all the string elements in these lists to uppercase. For example, consider the dictionary {'a': ['hello', 'world'], 'b': ['python', 'programming']}. We want to transform it into {'a': ['HELLO', 'WORLD'], 'b': ['PY
3 min read