Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to Pretty print Python dictionary from command line?
You can pretty print a Python dictionary using multiple approaches. The pprint module provides capability to "pretty-print" arbitrary Python data structures in a readable format, while the json module offers another elegant solution with customizable indentation.
Using pprint Module
The pprint module is specifically designed for pretty-printing Python data structures ?
import pprint
a = {
'bar': 22,
'foo': 45,
'nested': {'key1': 'value1', 'key2': 'value2'}
}
pprint.pprint(a, width=30)
{'bar': 22,
'foo': 45,
'nested': {'key1': 'value1',
'key2': 'value2'}}
Using json Module
The json module provides cleaner formatting with customizable indentation ?
import json
a = {
'bar': 22,
'foo': 45,
'nested': {'key1': 'value1', 'key2': 'value2'}
}
print(json.dumps(a, indent=4))
{
"bar": 22,
"foo": 45,
"nested": {
"key1": "value1",
"key2": "value2"
}
}
Command Line Usage
You can pretty print dictionaries directly from the command line using Python's -c flag ?
# Using pprint
python -c "import pprint; d={'a':1,'b':2}; pprint.pprint(d)"
# Using json
python -c "import json; d={'a':1,'b':2}; print(json.dumps(d, indent=2))"
Comparison
| Method | Output Format | Best For |
|---|---|---|
pprint |
Python syntax | Debugging Python objects |
json |
JSON format | Clean, readable output |
Conclusion
Use json.dumps() with indent parameter for cleanest output. Use pprint when working with complex Python objects that aren't JSON-serializable.
Advertisements
