How to Pretty print Python dictionary from command line?

PythonProgramming

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
}
raja
Published on 18-Apr-2018 13:08:04
Advertisements