The Wayback Machine - https://web.archive.org/web/20240926150409/https://www.geeksforgeeks.org/ways-to-convert-string-to-dictionary/
Open In App

Ways to convert string to dictionary

Last Updated : 01 Feb, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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

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 | 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
Convert Unicode String to Dictionary in Python
Python's versatility shines in its ability to handle diverse data types, with Unicode strings playing a crucial role in managing text data spanning multiple languages and scripts. When faced with a Unicode string and the need to organize it for effective data manipulation, the common task is converting it into a dictionary. In this article, we will
2 min read
Python | Pretty Print a dictionary with dictionary value
This article provides a quick way to pretty How to Print Dictionary in Python that has a dictionary as values. This is required many times nowadays with the advent of NoSQL databases. Let's code a way to perform this particular task in Python. Example Input:{'gfg': {'remark': 'good', 'rate': 5}, 'cs': {'rate': 3}} Output: gfg: remark: good rate: 5
7 min read
Python | Ways to Copy Dictionary
Dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. It is widely used in day to day programming, web development, and machine learning. When we simply assign dict1 = dict2 it refers to the same dictionary. Let's discuss a few ways to copy the
3 min read
Python | Ways to create a dictionary of Lists
Till now, we have seen the ways to create a dictionary in multiple ways and different operations on the key and values in the Python dictionary. Now, let's see different ways of creating a dictionary of lists. Note that the restriction with keys in the Python dictionary is only immutable data types can be used as keys, which means we cannot use a d
6 min read
Python | Ways to invert mapping of dictionary
Dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. It is widely used in day to day programming, web development, and machine learning. Let's discuss a few ways to invert mapping of a dictionary. Method #1: Using Dictionary Comprehension. C/C+
3 min read
Different ways of sorting Dictionary by Keys and Reverse sorting by keys
Prerequisite: Dictionaries in Python A dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. We can access the values of the dictionary using keys. In this article, we will discuss 10 different ways of sorting the Python dictionary by keys and a
8 min read
Python | Ways to remove a key from dictionary
Dictionary is used in manifold practical applications such as day-day programming, web development, and AI/ML programming as well, making it a useful container overall. Hence, knowing shorthands for achieving different tasks related to dictionary usage always is a plus. This article deals with one such task of deleting/removing a dictionary key-val
8 min read
Python | Convert a list of Tuples into Dictionary
Sometimes you might need to convert a tuple to dict object to make it more readable. In this article, we will try to learn how to convert a list of tuples into a dictionary. Here we will find two methods of doing this. Examples: Input : [("akash", 10), ("gaurav", 12), ("anand", 14), ("suraj", 20), ("akhil", 25), ("ashish", 30)] Output : {'akash': [
6 min read
Python | Convert list of tuple into dictionary
Given a list containing all the element and second list of tuple depicting the relation between indices, the task is to output a dictionary showing the relation of every element from the first list to every other element in the list. These type of problems are often encountered in Coding competition. Below are some ways to achieve the above task. I
8 min read
Convert nested Python dictionary to object
Let us see how to convert a given nested dictionary into an object Method 1 : Using the json module. We can solve this particular problem by importing the json module and use a custom object hook in the json.loads() method. C/C++ Code # importing the module import json # declaringa a class class obj: # constructor def __init__(self, dict1): self.__
2 min read
How to convert a dictionary into a NumPy array?
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 in the dictionary. Python provides numpy.array() method to convert a dictionary into NumPy array but before applying th
3 min read
How to convert a dictionary to a Pandas series?
Let's discuss how to convert a dictionary into pandas series in Python. A series is a one-dimensional labeled array which can contain any type of data i.e. integer, float, string, python objects, etc. while dictionary is an unordered collection of key : value pairs. We use series() function of pandas library to convert a dictionary into series by p
2 min read
How to convert NumPy array to dictionary in Python?
The following article explains how to convert numpy array to dictionary in Python. Array in Numpy is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers. In Numpy, number of dimensions of the array is called rank of the array. A tuple of integers giving the size of the array along each dimension is k
3 min read
Convert PySpark DataFrame to Dictionary in Python
In this article, we are going to see how to convert the PySpark data frame to the dictionary, where keys are column names and values are column values. Before starting, we will create a sample Dataframe: C/C++ Code # Importing necessary libraries from pyspark.sql import SparkSession # Create a spark session spark = SparkSession.builder.appName('DF_
3 min read
Convert Python Dictionary List to PySpark DataFrame
In this article, we will discuss how to convert Python Dictionary List to Pyspark DataFrame. It can be done in these ways: Using Infer schema.Using Explicit schemaUsing SQL Expression Method 1: Infer schema from the dictionary We will pass the dictionary directly to the createDataFrame() method. Syntax: spark.createDataFrame(data) Example: Python c
3 min read
How to convert a MultiDict to nested dictionary using Python
A MultiDict is a dictionary-like object that holds multiple values for the same key, making it a useful data structure for processing forms and query strings. It is a subclass of the Python built-in dictionary and behaves similarly. In some use cases, we may need to convert a MultiDict to a nested dictionary, where each key corresponds to a diction
3 min read
How to convert Dictionary to Pandas Dataframe?
Let’s discuss how to convert Python Dictionary to Pandas Dataframe. We can convert a dictionary to a Pandas dataframe by using the pd.DataFrame.from_dict() class-method. Convert Dictionary to Pandas Dataframe In Python ExamplesBelow are the ways by which we can convert dictionary to Pandas Dataframe in Python: Using pandas constructor (pd.DataFrame
2 min read
Python - Convert Lists to Nested Dictionary
Sometimes, while working with Python dictionaries, we can have a problem in which we need to convert lists to nestings, i.e. each list value represents a new nested level. This kind of problem can have applications in many domains including web development. Let's discuss the certain way in which this task can be performed. Convert Lists to Nested D
5 min read
Python | Convert list of nested dictionary into Pandas dataframe
Given a list of the nested dictionary, write a Python program to create a Pandas dataframe using it. We can convert list of nested dictionary into Pandas DataFrame. Let's understand the stepwise procedure to create a Pandas Dataframe using the list of nested dictionary. Convert Nested List of Dictionary into Pandas DataframeBelow are the methods th
4 min read
How To Convert Generator Object To Dictionary In Python
Generators in Python are powerful constructs for handling large datasets efficiently. However, there may be scenarios where you want to convert the output of a generator into a dictionary for easier manipulation and retrieval of data. In this article, we'll explore five different methods to convert a generator object to a dictionary in Python. Conv
3 min read
Pandas DataFrame to_dict() Method | Convert DataFrame to Dictionary
Python is a great language for doing data analysis because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.  Pandas .to_dict() method is used to convert a DataFrame into a dictionary of series or list-like data type depending on the orient parameter. Exam
3 min read
Convert JSON to dictionary in Python
JSON stands for JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the Python JSON package into Python script. The text in JSON is done through quoted-
4 min read
How To Convert Python Dictionary To JSON?
JSON stands for JavaScript Object Notation. It means that a script (executable) file made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-string which conta
7 min read
Python | Convert two lists into a dictionary
Interconversion between data types is usually necessary for real-time applications as certain systems have certain modules that require input in a particular data type. Let's discuss a simple yet useful utility of conversion of two lists into a key: value pair dictionary in Python. Converting Two Lists into a DictionaryPython List is a sequence dat
11 min read
Django - Convert form.errors to Python Dictionary
When working with Django forms, handling and displaying form validation errors efficiently is crucial for building user-friendly web applications. The form.errors attribute in Django provides error messages generated when a form is invalid. By default, form.errors returns an instance of ErrorDict, which is a specialized dictionary-like object. But
4 min read
Python | Ways to Convert a 3D list into a 2D list
List is a common type of data structure in Python. While we have used the list and 2d list, the use of 3d list is increasing day by day, mostly in case of web development. Given a 3D list, the task is to convert it into a 2D list. These type of problems are encountered while working on projects or while contributing to open source. Below are some w
3 min read
Convert Unicode String to a Byte String in Python
Python is a versatile programming language known for its simplicity and readability. Unicode support is a crucial aspect of Python, allowing developers to handle characters from various scripts and languages. However, there are instances where you might need to convert a Unicode string to a regular string. In this article, we will explore five diff
2 min read
Find the first repeated word in a string in Python using Dictionary
Prerequisite : Dictionary data structure Given a string, Find the 1st repeated word in a string. Examples: Input : "Ravi had been saying that he had been there" Output : had Input : "Ravi had been saying that" Output : No Repetition Input : "he had had he" Output : he We have existing solution for this problem please refer Find the first repeated w
4 min read