How do I serialize dicts in Python with examples?

In Python, you can serialize dictionaries (dicts) using the built-in `json` module, which converts a Python object into a JSON string. This process is often useful for saving data to a file or sending it over a network.

Here's a simple example of how to serialize a dictionary:

import json # Create a dictionary my_dict = { "name": "John", "age": 30, "city": "New York" } # Serialize dict to JSON string json_string = json.dumps(my_dict) print(json_string)

In this example, the `dumps` function of the `json` module is used to convert the dictionary `my_dict` into a JSON string. The output will be:

{"name": "John", "age": 30, "city": "New York"}

This serialized JSON string can then be saved to a file or sent to another application. You can also deserialize it back into a Python dictionary using the `loads` function.


python serialization serialize dict json module python dict to json