How to Print a Dictionary in One Line of Code in Python?

Estimated read time 1 min read

You can print a dictionary in one line of code in Python by using the print() function along with the dictionary name. Here’s an example:

my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
print(my_dict)

This will output the dictionary in the following format:

{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

However, if you want to print the dictionary in a more readable format on one line, you can use the json module in Python to pretty-print the dictionary. Here’s an example:

import json

my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
print(json.dumps(my_dict))

This will output the dictionary in the following format:

{"key1": "value1", "key2": "value2", "key3": "value3"}

Note that the keys and values are now enclosed in double quotes, as is required by the JSON format.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply