How to Convert String to Dictionary in Python

Here are ways to convert string to dictionary in Python:

  1. Using json.loads()
  2. Using ast.literal.eval()
  3. Using split()
  4. Using eval()

Method 1: Using json.loads() 

If your string is in JSON format, you can use the json.loads() method.

Visual Representation

Visual Representation of Convert String to Dictionary

Example

import json

str = '{"Name": "Millie", "Age": 18, "City": "Atlanta"}'
print('The JSON String is', str)
print(type(str))

# Convert to a dictionary 
dict = json.loads(str)

print("Converted dictionary: ", dict)
print(type(dict))

Output

The JSON String is {"Name": "Millie", "Age": 18, "City": "Atlanta"}
<class 'str'>
Converted dictionary: {'Name': 'Millie', 'Age': 18, 'City': 'Atlanta'}
<class 'dict'>

Method 2: ast.literal_eval()

The ast.literal_eval() function from ast module, safely converts a string into a dictionary by evaluating literals and containers (such as dictionaries, lists, tuples, and strings), without executing arbitrary code.

Visual Representation

Visual Representation of Using ast.literal_eval()

Example

import ast

str = '{"Name": "Millie", "Age": 18, "City": "Atlanta"}'
print('The JSON String is', str)
print(type(str))

# Convert to a dictionary
dict = ast.literal_eval(str)

print("Converted dictionary: ", dict)
print(type(dict))

Output

The JSON String is {"Name": "Millie", "Age": 18, "City": "Atlanta"}
<class 'str'>
Converted dictionary: {'Name': 'Millie', 'Age': 18, 'City': 'Atlanta'}
<class 'dict'>

Method 3: Using split()

The split() method is suitable for strings that are not in JSON format.

Example

str = "Name: Millie, Age: 18, City: Atlanta"
print('The String is ===', str) 
print(type(str))

# Splitting the string on comma and then on colon to create key-value pairs
dict_data = dict(item.split(": ") for item in str.split(", "))

print("Converted dictionary: ", dict_data)
print(type(dict_data))

Output

The String is === Name: Millie, Age: 18, City: Atlanta
<class 'str'>
Converted dictionary: {'Name': 'Millie', 'Age': '18', 'City': 'Atlanta'}
<class 'dict'>

Method 4: Using eval()

The eval() function can be dangerous when used with untrusted input, as it can execute arbitrary code. It should only be used if you are sure that the input is safe and trusted.

Visual Representation

Visual Representation of Using eval()

Example

str = '{"Name": "Millie", "Age": 18, "City": "Atlanta"}'
print('The JSON String is === ', str)
print(type(str))

# Convert to a dictionary
dict = eval(str)

print("Converted dictionary: ", dict)
print(type(dict))

Output

The JSON String is === {"Name": "Millie", "Age": 18, "City": "Atlanta"}
<class 'str'>
Converted dictionary: {'Name': 'Millie', 'Age': 18, 'City': 'Atlanta'}
<class 'dict'>

Related posts

Python string to list

Python string to array

Python string to dict

Python string to hex

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.