5 Best Ways to Convert String Dictionary to Dictionary in Python

πŸ’‘ Problem Formulation: In Python, it’s common to encounter a situation where you have a dictionary represented as a string and you need to convert it back into a usable dictionary object. For example, you might have the string dictionary "{'key': 'value', 'number': 42}" and want to convert it to a Python dictionary object {'key': 'value', 'number': 42} for further manipulation. In this article, we’ll explore five ways to achieve this.

Method 1: Using json.loads()

This method is straightforward and quite common. The json.loads() function from the ‘json’ module can decode a string that contains a JSON document into a Python dictionary. It is important that the string is JSON-formatted, which means it uses double quotes for strings.

β™₯️ Info: Are you AI curious but you still have to create real impactful projects? Join our official AI builder club on Skool (only $5): SHIP! - One Project Per Month

Here’s an example:

import json

str_dict = '{"key": "value", "number": 42}'
converted_dict = json.loads(str_dict)

print(converted_dict)

Output:

{'key': 'value', 'number': 42}

This method is highly reliable for strings formatted in JSON, which requires double quotes around the keys and values. It fails with single-quoted strings and does not handle Python-specific object types.

Method 2: Using ast.literal_eval()

The ast.literal_eval() function safely evaluates a string containing a Python literal or container display. This method supports strings with single or double quotes and is safer than eval(), as it does not execute the code.

Here’s an example:

import ast

str_dict = "{'key': 'value', 'number': 42}"
converted_dict = ast.literal_eval(str_dict)

print(converted_dict)

Output:

{'key': 'value', 'number': 42}

This method is superior when dealing with Python’s native dictionary syntax and is safe for untrusted input. However, performance might be an issue with very large strings.

Method 3: Using eval()

Although generally discouraged due to security risks, eval() is a built-in function that can parse a string as Python code. This method is useful for strings that are not JSON formatted and contain Python-style dictionaries.

Here’s an example:

str_dict = "{'key': 'value', 'number': 42}"
converted_dict = eval(str_dict)

print(converted_dict)

Output:

{'key': 'value', 'number': 42}

This code snippet should be used cautiously as eval() can execute arbitrary code, which can lead to security vulnerabilities. It’s typically best reserved for trusted or sanitized input.

Method 4: Using yaml.safe_load()

The yaml.safe_load() function from the ‘yaml’ module can parse a string into a Python dictionary. It can handle more diverse data structures than JSON, and like ast.literal_eval(), it is designed to be safe for untrusted input.

Here’s an example:

import yaml

str_dict = "key: value\nnumber: 42"
converted_dict = yaml.safe_load(str_dict)

print(converted_dict)

Output:

{'key': 'value', 'number': 42}

This method works well even when the string is not strictly JSON or Python dict formatted, and it also handles complex structures. However, it requires the PyYAML package to be installed.

Bonus One-Liner Method 5: Using Comprehension and split()

This is a quick and dirty one-liner method that uses a dictionary comprehension combined with string methods like split() to convert simple dictionary strings.

Here’s an example:

str_dict = "key1:value1,key2:value2"
converted_dict = {k: v for k, v in (item.split(':') for item in str_dict.split(','))}

print(converted_dict)

Output:

{'key1': 'value1', 'key2': 'value2'}

This method is best suited for simple serialized forms that are not JSON, without nested structures. However, it lacks flexibility and error handling, making it unsuitable for complex strings.

Summary/Discussion

  • Method 1: json.loads(). This is great for JSON-formatted strings and is quick and reliable. It does not handle Python-specific datatypes.
  • Method 2: ast.literal_eval(). Perfect for Python-formatted strings and safer than eval(). Can be slow for large strings.
  • Method 3: eval(). Works with Python syntax but poses security concerns, and should only be used with trusted input.
  • Method 4: yaml.safe_load(). Excellent for a wider range of data structures but requires an external library.
  • Method 5: Comprehension and split(). A simple and fast solution for non-nested, non-JSON strings but not as robust or secure as other methods.