Create a Dictionary from a String
Last Updated :
28 Jan, 2025
The task of creating a dictionary from a string in Python often involves converting a string representation of a dictionary into an actual Python dictionary.
For example, a string like "{'A':13, 'B':14, 'C':15}" represents a dictionary with keys 'A', 'B', and 'C' mapped to their respective values. The goal here is to transform this string into a Python dictionary. After the transformation, the dictionary will look like this: {'A': 13, 'B': 14, 'C': 15}.
Using ast.literal_eval()
ast.literal_eval() is a efficient method to evaluate strings containing Python literals. It can convert strings that represent basic Python data structures such as dictionaries, lists and tuple into their corresponding Python objects. Unlike eval(), ast.literal_eval() is much safer as it only evaluates literals and does not allow execution of arbitrary code.
Python
import ast
s = "{'A':13, 'B':14, 'C':15}"
res = ast.literal_eval(s)
print(res, type(res))
Output{'A': 13, 'B': 14, 'C': 15} <class 'dict'>
Explanation: ast.literal_eval(s) to safely convert the string s into a dictionary. It evaluates the string as a Python literal, ensuring security by only allowing basic data structures. The result is stored in res .
Using json.loads()
json.loads() from the json module that parses a string in JSON format and converts it into a Python dictionary. While json.loads() is primarily designed for working with JSON data, it can also be used for parsing dictionaries if the string uses double quotes as JSON format requires .
Python
import json
s = "{'A':13, 'B':14, 'C':15}".replace("'", '"')
res = json.loads(s)
print(res,type(res))
Output{'A': 13, 'B': 14, 'C': 15} <class 'dict'>
Explanation: This code replaces single quotes with double quotes to make the string JSON-valid, then uses json.loads() to parse it into a Python dictionary. The result is printed along with its type.
Using eval()
eval() is a built-in Python function that parses and evaluates a string as a Python expression. It can handle complex expressions and can be used to evaluate a string representation of a dictionary. However, eval() poses significant security risks when used with untrusted input, as it allows the execution of arbitrary code.
Python
s = "{'A':13, 'B':14, 'C':15}"
res = eval(s)
print(res)
Output{'A': 13, 'B': 14, 'C': 15}
Explanation: eval(s) evaluate the string s as a Python expression. Since the string s represents a dictionary, eval() converts it into an actual Python dictionary. The result is stored in res .
Using exec()
exec() is another Python built-in function, similar to eval(), but is more general-purpose. It can execute arbitrary Python code and is used when the code in the string may contain multiple Python statements. Like eval(), exec() comes with the same security risks when working with untrusted input.
Python
s = "{'A':13, 'B':14, 'C':15}"
exec(f"res = {s}")
print(res)
Output{'A': 13, 'B': 14, 'C': 15}
Explanation: This code uses f"res = {s}" to embed the string s into an assignment expression and exec() then executes this string as Python code, assigning the dictionary to res.
Similar Reads
Create Dictionary from the List-Python The task of creating a dictionary from a list in Python involves mapping each element to a uniquely generated key, enabling structured data storage and quick lookups. For example, given a = ["gfg", "is", "best"] and prefix k = "def_key_", the goal is to generate {'def_key_gfg': 'gfg', 'def_key_is':
3 min read
Dictionary Creation Programs Dictionaries are one of the most essential data structures in Python, allowing us to store and manage data using key-value pairs. But before we can use them, we first need to create dictionaries efficiently based on different requirements, whether it's from lists, strings, tuples, text files, or eve
1 min read
How to Create a Python Dictionary from Text File? The task of creating a Python dictionary from a text file involves reading its contents, extracting key-value pairs and storing them in a dictionary. Text files typically use delimiters like ':' or ',' to separate keys and values. By processing each line, splitting at the delimiter and removing extr
3 min read
Create Dictionary Of Tuples - Python The task of creating a dictionary of tuples in Python involves mapping each key to a tuple of values, enabling structured data storage and quick lookups. For example, given a list of names like ["Bobby", "Ojaswi"] and their corresponding favorite foods as tuples [("chapathi", "roti"), ("Paraota", "I
3 min read
Create Dynamic Dictionary in Python Creating a Dynamic Dictionary in Python is important in programming skills. By understanding how to generate dictionaries dynamically, programmers can efficiently adapt to changing data requirements, facilitating flexible and responsive code development. In this article, we will explore different me
3 min read
Python - Convert Dictionary to Concatenated String In Python, sometimes we need to convert a dictionary into a concatenated string. The keys and values of the dictionary are combined in a specific format to produce the desired string output. For example, given the dictionary {'a': 1, 'b': 2, 'c': 3}, we may want the string "a:1, b:2, c:3". Let's dis
3 min read