How to convert a dictionary to a string in the Python language?

  In Python, a dictionary is a very common data type, which consists of an unordered collection of key-value pairs. Sometimes it is necessary to convert a dictionary into a string for use in network transmission, file storage, and other occasions. So how to convert the dictionary into a string format? The following are the details:

  1. Use the json library

  JSON is a lightweight data interchange format that converts Python objects into strings and transmits them. In Python, a dictionary can be converted to a string using the dumps() method from the json library. The parameters of the dumps() method include the Python object to be converted and some optional parameters, the most commonly used parameters are indent and ensure_ascii.

  Code example:

  import json

  dict_data = {'name': 'Alice', 'age': 18} str_data = json.dumps(dict_data, indent=4. ensure_ascii=False) print(str_data)

  2. Use the str() function

  In Python, any object can be converted to a string using the str() function. For a dictionary object, the str() function converts it into a string similar to Python code, which includes the key-value pairs of the dictionary.

  Code example:

  dict_data = {'name': 'Bob', 'age': 20}

  str_data = str(dict_data)

  print(str_data)

  3. Use the ast.literal_eval() function

  ast is a built-in module of Python that contains some tools for abstract syntax tree manipulation. The ast.literal_eval() function converts a string into a Python object, including a dictionary object. Unlike the eval() function, the ast.literal_eval() function can only parse some simple Python expressions and will not execute arbitrary code, so it is safer and more reliable.

  Code example:

  import ast

  str_data = "{'name': 'Charlie', 'age': 22}"

  dict_data = ast.literal_eval(str_data)

  print(dict_data)

  4. Use the eval() function

  The eval() function is a very powerful function in Python, which can execute arbitrary Python code and return the execution result. For dictionary objects, you can use the eval() function to convert it to a string. It should be noted that the eval() function needs to be used with great care, as it can execute arbitrary code, which may lead to security holes.

  Code example:

  dict_data = {'name': 'David', 'age': 24}

  str_data = eval(str(dict_data))

  print(str_data)

Guess you like

Origin blog.csdn.net/oldboyedu1/article/details/131434904