Creating A Dictionary From A String In Python

In this tutorial, we will be creating a dictionary from a string in python. Dictionary is a very useful data structure in python and quite often we need to convert a string into a dictionary. This string is of a dictionary format or similar to it. We will be going through two methods to create a dictionary from a string.

How to Create A Dictionary From A String

We will create a dictionary from a string in two different ways.

 

Using eval() function

One scenario is that the inputted string completely resembles a dictionary object (key value pair with colon and each pair separated by commas and all the elements inside curly brace). Then this string can be converted to a dictionary easily using the eval() function.

str1 = "{ 1:'Jan', 2:'Feb', 3:'Mar'}"

dictionary = eval(str1)
print(dictionary)
print(dictionary[1])

Here, the string str1 completely resembles a dictionary object, so we use eval() to convert it to a dictionary. We are checking if the code works by printing the dictionary and also the value corresponding to the key 1. From the output we can see that the function eval() works.

{1: 'Jan', 2: 'Feb', 3: 'Mar'}
Jan

By splitting string

If the input string does not completely resemble a dictionary object then we can split the string to convert it to a dictionary. Let the string have key-value pair separated by ‘-‘ instead of ‘:’ but the elements are separated by commas. Also, these elements are not inside curly braces. Then we will split the string and individually put a key value pair in the dictionary. But, here all keys and values will be strings.

string = "1 - Jan, 2 - Feb, 3 - Mar"
  
dictionary = dict((a.strip(), b.strip()) for a, b in (member.split('-') for member in string.split(', '))) 
  
print(dictionary) 
print(dictionary['1'])

Here, we use strip() and split() to breakdown the string and pass on the keys and values to the dictionary with the help of dict(). strip() strips an element by removing both leading and trailing characters, split() splits a string and dict() creates a dictionary. We are checking if the code works by printing the dictionary and also the value corresponding to the key 1. From the output, we can see that our code works.

{'1': 'Jan', '2': 'Feb', '3': 'Mar'}
Jan

So here are two simple methods to create a dictionary from a string.

Also read,

Creation, Addition, Removal and Modification of Dictionary in Python

Sort Words in a List in Alphabetical Order in Python

Leave a Reply

Your email address will not be published. Required fields are marked *