![]() |
VOOZH | about |
In Python, there are situations where we need to convert a dictionary into a string format. For example, given the dictionary {'a' : 1, 'b' : 2} the objective is to convert it into a string like "{'a' : 1, 'b' : 2}".
Let's discuss different methods to achieve this:
The simplest way to convert a dictionary to a string is by using the built-in function "str()" for string conversion.
{'a': 1, 'b': 2} <class 'str'>
Explanation:str() function converts the dictionary into its string representation.
Another method is to use the dumps function from the json module for converting a dictionary into a JSON-formatted string.
{"a": 1, "b": 2}
Explanation:
This method uses repr() function and converts the dictionary into a string representation that can be evaluated back into a dictionary.
{'a': 1, 'b': 2}
Explanation:
str.This method manually constructs the string representation of the dictionary by concatenating its key-value pairs.
{'a': 1, 'b': 2}
Explanation: