Fundamentals of Python Programming

Converting String to Dictionary in Python

Converting String to Dictionary in Python

Introduction

A reliable data structure for working with key-value pairs is the Python dictionary. However, json string is employed for sending data back and forth between the client and server. When data is accessible on the client side, we must translate the JSON string into a dictionary because it is a standard for data sharing. Given a dictionary's string representation. How can it be made into a dictionary?

Input:
'{"1": "hi", "2": "alice", "3": "python"}'

Output:
{'a': 1, 'b': 2, 'c': 3}

Method 1: eval()

The built-in eval() method accepts a string parameter and parses it to make it look like a code expression before evaluating it. The return value is a standard Python dictionary if the string provides a textual representation of a dictionary. By using the eval() method, you may quickly turn a text into a Python dictionary.

s = '{"1": "hi", "2": "alice", "3": "python"}'

d = eval(s)

print(d)
print(type(d))
The output is:


{'1': 'hi', '2': 'alice', '3': 'python'}
<class 'dict'>

Method 2: ast.literal_eval()

A string literal, such as a dictionary represented by a string, or an expression can be securely evaluated using the ast.literal eval() function. It addresses many of the security issues with the eval() function and is also appropriate for strings that may originate from unreliable sources. By using the expression ast.literal eval, you may transform a dictionary's string representation

import ast

s = '{"1": "hi", "2": "alice", "3": "python"}'
d = ast.literal_eval(s)

print(d)
print(type(d))
The output is:
{'1': 'hi', '2': 'alice', '3': 'python'}
<class 'dict'>

Method 3: json.loads() & s.replace()

Use the json.loads() function on a string to transform a dict's representation into a dict. First, use the expression s.replace( to convert all single quote characters to escaped double quote characters "'", """) to make it compatible with Python's JSON module. The command "json.loads(s.replace("'", "" ")) creates a dictionary from the string s.

import json

s = '{"1": "hi", "2": "alice", "3": "python"}'

d = json.loads(s.replace("'", """))

print(d)
print(type(d))
The output is:
{'1': 'hi', '2': 'alice', '3': 'python'}
<class 'dict'>

write your code here: Coding Playground

Unfortunately, this approach is subpar since it will not work for dictionary representations when the keys or values have trailing commas or single quotes. It's not the easiest one either, which is why technique 1's broad strategy is chosen.

Method 4: Iterative Approach

A string may also be turned into a dictionary by breaking it up into a series of (key, value) pairs. After some cleanup, you may add every (key, value) pair to an originally empty dictionary. Here is a simple Python implementation:

s = '{"1": "hi", "2": "alice", "3": "python"}'

def string_to_dict(s):
new_dict = {}

# Determine key, value pairs
mappings = s.replace('{', '').replace('}', '').split(',')

for x in mappings:
key, value = x.split(':')

# Automatically convert (key, value) pairs to correct type
key, value = eval(key), eval(value)

# Store (key, value) pair
new_dict[key] = value

return new_dict


d = string_to_dict(s)

print(d)
print(type(d))
The output is:


{'1': 'hi', '2': 'alice', '3': 'python'}
<class 'dict'>

write your code here: Coding Playground