How to Pretty print Python dictionary from command line?


You can pretty print a dict in python using the pprint library. The pprint module provides a capability to “pretty-print” arbitrary Python data structures in a form which can be used as input to the interpreter. You can use it as follows

Example

a = {
   'bar': 22,
   'foo': 45
}
pprint.pprint(a, width=10)

Output

This will give the output:

{'bar': 22,
'foo': 45}

As you can see that even this can be unreadable. You can use the json module to actually print it better. For example,

Example

import json
a = {
   'bar': 22,
   'foo': 45
}
print(json.dumps(a, indent=4))

Output

This will give the output:

{
   "bar": 22,
   "foo": 45
}

Updated on: 17-Jun-2020

596 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements