Answered on : 2024-01-24
To print a Python dictionary as JSON, you can use the `json` module. Here's a simple guide:
1. Import the `json` module in your Python script.
```python
import json
```
2. Use the `json.dumps()` function to convert the dictionary to a JSON-formatted string.
```python
my_dict = {"key": "value", "number": 42}
json_string = json.dumps(my_dict)
```
3. If you want to pretty print the JSON for better readability, you can use the `indent` parameter in `json.dumps()`.
```python
pretty_json_string = json.dumps(my_dict, indent=4)
```
Remember to replace `my_dict` with the name of your dictionary.
This process involves importing the `json` module, using `json.dumps()` to convert the dictionary, and optionally using `indent` for better formatting [1] [3] [6].