Open In App

Ways to convert string to dictionary

Last Updated : 01 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Dictionary is an unordered collection in Python that store data values like a map i.e., key: value pair. In order to convert a String into a dictionary, the stored string must be in such a way that key: value pair can be generated from it. This article demonstrates several ways of converting a string into a dictionary. 

Method 1: Splitting a string to generate a key: value pair of the dictionary In this approach, the given string will be analyzed and with the use of the split() method, the string will be split in such a way that it generates the key: value pair for the creation of a dictionary. Below is the implementation of the approach. 

Python3




# Python implementation of converting
# a string into a dictionary
 
# initialising string
str = " Jan = January; Feb = February; Mar = March"
 
# At first the string will be splitted
# at the occurrence of ';' to divide items
# for the dictionaryand then again splitting
# will be done at occurrence of '=' which
# generates key:value pair for each item
dictionary = dict(subString.split("=") for subString in str.split(";"))
 
# printing the generated dictionary
print(dictionary)


Output

{' Jan ': ' January', ' Feb ': ' February', ' Mar ': ' March'}

Time Complexity: O(n), where n is the number of items in the input string.
Auxiliary Space: O(n), as it creates a dictionary with n key-value pairs.
 

Method 2: Using 2 strings to generate the key:value pair for the dictionary In this approach, 2 different strings will be considered and one of them will be used to generate keys and another one will be used to generate values for the dictionary. After manipulating both the strings the dictionary items will be created using those key:value pair. Below is the implementation of the approach. 

Python3




# Python implementation of converting
# a string into a dictionary
 
# initialising first string
str1 = "Jan, Feb, March"
str2 = "January | February | March"
 
# splitting first string
# in order to get keys
keys = str1.split(", ")
 
# splitting second string
# in order to get values
values = str2.split("|")
 
# declaring the dictionary
dictionary = {}
 
# Assigning keys and its
# corresponding values in
# the dictionary
for i in range(len(keys)):
    dictionary[keys[i]] = values[i]
 
# printing the generated dictionary
print(dictionary)


Output

{'Jan': 'January ', 'Feb': ' February ', 'March': ' March'}

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

Method 3: Using zip() method to combine the key:value pair extracted from 2 string In this approach, again 2 strings will be used, one for generating keys and another for generating values for the dictionary. When all the keys and values are stored, zip() method will be used to create key:value pair and thus generating the complete dictionary. Below is the implementation of the approach. 

Python3




# Python implementation of converting
# a string into a dictionary
 
# initialising first string
str1 = "Jan, Feb, March"
str2 = "January | February | March"
 
# splitting first string
# in order to get keys
keys = str1.split(", ")
 
# splitting second string
# in order to get values
values = str2.split("|")
 
# declaring the dictionary
dictionary = {}
 
# Assigning keys and its
# corresponding values in
# the dictionary
dictionary = dict(zip(keys, values))
 
# printing the generated dictionary
print(dictionary)


Output

{'Jan': 'January ', 'Feb': ' February ', 'March': ' March'}

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

Method 4: If the string is itself in the form of string dictionary In this approach, a string which is already in the form of string dictionary i.e., the string has a dictionary expression is converted into a dictionary using ast.literal_eval() method. Below is the implementation of the approach. 

Python3




# Python implementation of converting
# a string into a dictionary
 
# importing ast module
import ast
 
# initialising string dictionary
str = '{"Jan" : "January", "Feb" : "February", "Mar" : "March"}'
 
# converting string into dictionary
dictionary = ast.literal_eval(str)
 
# printing the generated dictionary
print(dictionary)


Output

{'Jan': 'January', 'Feb': 'February', 'Mar': 'March'}

The Time and Space Complexity for all the methods are the same:

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

Method  5 : Using split(),index() and slicing 

Python3




# Python implementation of converting
# a string into a dictionary
 
# initialising string
str = " Jan = January; Feb = February; Mar = March"
 
res=dict()
x=str.split(";")
for i in x:
    a=i[:i.index("=")]
    b=i[i.index("=")+1:]
    res[a]=b
# printing the generated dictionary
print(res)


Output

{' Jan ': ' January', ' Feb ': ' February', ' Mar ': ' March'}

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



Similar Reads

Convert String Dictionary to Dictionary Python
Interconversions of data types have been discussed many times and have been quite a popular problem to solve. This article discusses yet another problem of interconversion of the dictionary, in string format to a dictionary. Let's discuss certain ways in which this can be done. Convert String Dictionary to Dictionary Using json.loads() This task ca
6 min read
Python | Convert flattened dictionary into nested dictionary
Given a flattened dictionary, the task is to convert that dictionary into a nested dictionary where keys are needed to be split at '_' considering where nested dictionary will be started. Method #1: Using Naive Approach Step-by-step approach : Define a function named insert that takes two parameters, a dictionary (dct) and a list (lst). This functi
8 min read
Python | Convert nested dictionary into flattened dictionary
Given a nested dictionary, the task is to convert this dictionary into a flattened dictionary where the key is separated by '_' in case of the nested key to be started. Method #1: Using Naive Approach Step-by-step approach : The function checks if the input dd is a dictionary. If it is, then it iterates over each key-value pair in the dictionary, a
8 min read
Convert Dictionary Value list to Dictionary List Python
Sometimes, while working with Python Dictionaries, we can have a problem in which we need to convert dictionary list to nested records dictionary taking each index of dictionary list value and flattening it. This kind of problem can have application in many domains. Let's discuss certain ways in which this task can be performed. Input : test_list =
9 min read
Different ways to convert a Python dictionary to a NumPy array
In this article, we will see Different ways to convert a python dictionary into a Numpy array using NumPy library. It’s sometimes required to convert a dictionary in Python into a NumPy array and Python provides an efficient method to perform this operation. Converting a dictionary to NumPy array results in an array holding the key-value pairs of t
3 min read
Python | Ways to split a string in different ways
The most common problem we have encountered in Python is splitting a string by a delimiter, But in some cases we have to split in different ways to get the answer. In this article, we will get substrings obtained by splitting string in different ways. Examples: Input : Paras_Jain_Moengage_best Output : ['Paras', 'Paras_Jain', 'Paras_Jain_Moengage',
2 min read
Python | Convert dictionary object into string
The dictionary is an important container and is used almost in every code of day-to-day programming as well as web development with Python. The more it is used, the more is the requirement to master it and hence it's necessary to learn about them. Input: { "testname" : "akshat","test2name" : "manjeet","test3name" : "nikhil"}Output: {"testname": "ak
3 min read
Python | Convert byteString key:value pair of dictionary to String
Given a dictionary having key:value pairs as byteString, the task is to convert the key:value pair to string. Examples: Input: {b'EmplId': b'12345', b'Name': b'Paras', b'Company': b'Cyware' } Output: {'EmplId': '12345', 'Name': 'Paras', 'Company': 'Cyware'} Input: {b'Key1': b'Geeks', b'Key2': b'For', b'Key3': b'Geek' } Output: {'Key1':'Geeks', 'Key
4 min read
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
5 min read
Python - Convert Dictionary to Concatenated String
Sometimes, while working with Dictionaries, we can have a task in which we need to perform the conversion of converting dictionary to string, which is concatenated key-value pair. This can have application in domains in which we require to reduce storage space or require strings as target data. Let's discuss certain ways in which this task can be p
6 min read