In this article, I will tell you how to use the ast.literal_eval()
method convert strings to dictionary in python. I will also tell you how to use the dict() function to convert numbers, tuples to dictionary in python with examples.
1. How To Use ast.literal_eval() To Convert String To Dictionary In Python.
- To convert a Python string to a dictionary, you need to use the
ast.literal_eval()
method. - This method will evaluate a string containing a Python literal or container and return a Python object.
1.1 The Python ast.literal_eval() Method Description.
- The
ast.literal_eval()
method is a built-in Python function that evaluates a string containing a literal expression and returns the resulting value. - It is used to safely evaluate strings containing Python expressions from untrusted sources without the need for manual string escaping.
- It is similar to the eval() function, but it only evaluates Python literals such as strings, numbers, tuples, lists, dicts, booleans, and None.
1.2 How To Use ast.literal_eval() To Convert String To Dictionary Example.
- Here is an example of how to use
ast.literal_eval()
to convert a string to a dictionary.import ast # a Python string containing a dictionary string = "{'a': 1, 'b': 2}" # convert the string to a dictionary dictionary = ast.literal_eval(string) # print the dictionary print(dictionary)
- The output of this code will be
{'a': 1, 'b': 2}
.
2. How To Use The dict() Function To Convert Numbers, Tuples To Dictionary In Python.
- Converting a Python number to a dictionary is relatively simple and can be done using the
dict()
function.
2.1 The Python dict() Method Description.
- The
dict()
method is a built-in Python function that creates a dictionary from a given sequence of elements. - It takes a sequence of key-value pairs and returns a dictionary with the same key-value pairs.
- The keys must be hashable objects, such as strings, numbers, or tuples, and the values can be any Python object.
- The dict() method is often used to create a dictionary from a list of tuples.
2.2 How To Use dict() To Convert Number, Tuples To Dictionary Example.
2.2.1 Convert Number To Dictionary Object.
- To illustrate, consider the following example code, it will convert a number to a dictionary object in python using the dict() method.
# A sample Python number my_number = 4 # Converting the number to a dictionary my_dict = dict(number = my_number) # Print the dictionary print(my_dict)
- The output of this code will be.
{'number': 4}
2.2.2 Convert Tuples To Dictionary Object.
- You can also use the dict() function to convert a list of tuples to a dictionary.
- For example, the following code will create a dictionary from a list of tuples.
# A sample list of tuples my_lst = [("name", "John"), ("age", 20)] # Converting the list to a dictionary my_dict = dict(my_lst) # Print the dictionary print(my_dict)
- The output will be.
{'name': 'John', 'age': 20}