446

How can I pretty print a dictionary with depth of ~4 in Python? I tried pretty printing with pprint(), but it did not work:

import pprint 
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(mydict)

I simply want an indentation ("\t") for each nesting, so that I get something like this:

key1
    value1
    value2
    key2
       value1
       value2

etc.

How can I do this?

martineau
  • 112,593
  • 23
  • 157
  • 280
  • 43
    What does "did not work" mean? Please specify very precisely how pprint "did not work". – S.Lott Jul 12 '10 at 14:43
  • 6
    I have now used 3 of these answers (each good in a specific scenario): [@Ken's json answer](http://stackoverflow.com/a/3314411/52074) is good but fails sometimes when the object can't be json serializable (throws exception). if @Ken's json answer doesn't work try [@Andy's yaml answer](http://stackoverflow.com/a/14892136/52074) and it should work but the string output is a little less human readable. [@sth's answer] is the most generic (should work for any object and doesn't use any libs). – Trevor Boyd Smith Nov 11 '16 at 19:43
  • I think you should try to find a proper the `width` parameter. Check out the [description](https://docs.python.org/3/library/pprint.html#pprint.PrettyPrinter) – Ersel Er Nov 06 '20 at 16:58
  • what is wrong with pretty print? `import pprint.pprint as pprint;pprint(d)`? – Charlie Parker Sep 16 '21 at 17:53

26 Answers26

704

My first thought was that the JSON serializer is probably pretty good at nested dictionaries, so I'd cheat and use that:

>>> import json
>>> print(json.dumps({'a':2, 'b':{'x':3, 'y':{'t1': 4, 't2':5}}},
...                  sort_keys=True, indent=4))
{
    "a": 2,
    "b": {
        "x": 3,
        "y": {
            "t1": 4,
            "t2": 5
        }
    }
}
Mike Pennington
  • 40,496
  • 17
  • 132
  • 170
Ken
  • 8,559
  • 2
  • 15
  • 14
  • 62
    This is cool, but doesn't print all dictionaries well. print json.dumps(myObject.__dict__, sort_keys=True, indent=4) #TypeError: is not JSON serializable – tponthieux Feb 08 '12 at 23:30
  • @RocketDonkey: It should work with almost any subclass of `dict`. I just tried it with my custom [`OrderedDefaultdict`](http://stackoverflow.com/a/4127426/355230) with no problems. – martineau May 24 '13 at 02:22
  • 7
    While this looks useful, it's output is not what the OP wanted. – martineau May 24 '13 at 03:28
  • 3
    @martineau: The OP's requested output doesn't make sense, dictionaries need keys per value. – naught101 Oct 02 '13 at 04:28
  • 2
    @naught101: A pretty printer can do whatever is needed to produce the output desired. – martineau Oct 02 '13 at 07:57
  • used pretty printer to produce this: `{ 0: { 0: { (0, 0): 1}}, 1: { 0: { (0, 1): 1, (1, 0): 1}}}`. `json.dumps` gave me: `TypeError: key (0, 0) is not a string` – juggler Jan 02 '14 at 21:10
  • 36
    json.dumps takes a conversion function as an optional argument, so with json.dumps(myObject.__dict__, sort_keys=True, indent=4, deault=str) you can at least use an objects implementation of __repr__ to print itself and get round the 'not JSON serializable' TypeError – RFairey Sep 23 '14 at 16:20
  • Using json is a neat trick but can work in all case, functions and ojects are translated into string using RFairey trick, dict key don't keep their type, and tuples are changed into lists. YOu can look at my solution for a result that corespond to original results of the python interpreter but pretty printed. – y.petremann Oct 06 '14 at 04:42
  • 1
    +1 @RFairey Thanks for the awesome tip. I used `repr` instead of `str` but I cant imagine why is this neither the default, nor even mentioned anywhere in the documentation.I assumed making an Encoder class was the only choice.. – Karthik T Aug 31 '15 at 06:52
  • To pretty print some python output quickly, copy from console to here: http://www.cleancss.com/python-beautify/ Very nice :) – radtek Jun 23 '16 at 21:59
  • This really deserved the answer for this question. – Calvin Ellington Feb 16 '18 at 17:15
  • None gets printed as null, which also sucks. – John Jiang Feb 26 '21 at 06:18
  • Doesn't work if your dictionary contains binary values – quickinsights May 27 '22 at 18:46
200

I'm not sure how exactly you want the formatting to look like, but you could start with a function like this:

def pretty(d, indent=0):
   for key, value in d.items():
      print('\t' * indent + str(key))
      if isinstance(value, dict):
         pretty(value, indent+1)
      else:
         print('\t' * (indent+1) + str(value))
sth
  • 211,504
  • 50
  • 270
  • 362
  • 13
    U know @Ken's conventional answer is much better than this. Json already handles everything and this can give errors such: **UnicodeEncodeError: 'ascii' codec can't encode character u'\xf3' in position 50: ordinal not in range(128)** – wonderwhy Aug 27 '14 at 13:20
  • I can't make it works with the nested dict of my solution, because it gave me a UnicodeEncodeError, also it don't print dict key, don't go inside list and tuples and don't keep a python valid syntax. – y.petremann Oct 06 '14 at 04:33
  • This answer worked like a charm for me, however I posted a new question https://stackoverflow.com/questions/36972225/pretty-print-nested-dictionary-with-a-limit which sets a limit to how many values should be printed. – gsamaras May 01 '16 at 21:34
  • Pretty good. If you've got nested lists like in the OP's question, you need to add some handling for that. If you're having issues in Py2, it's cause it can't handle Unicode properly without hacks like `__future__` that the answer now mentions, so you have to employ those wherever needed (or update to 3 already). – sudo Feb 14 '18 at 18:10
  • 1
    This worked well enough for me : ```python def pretty(d, indent=0): for key, value in d.items(): if isinstance(value, dict): print(' ' * indent + str(key)) pretty(value, indent+1) else: print(' ' * (indent+1) + f"{key}: {value}") ``` – hum3 Apr 27 '20 at 11:13
87

You could try YAML via PyYAML. Its output can be fine-tuned. I'd suggest starting with the following:

print yaml.dump(data, allow_unicode=True, default_flow_style=False)

The result is very readable; it can be also parsed back to Python if needed.

Edit:

Example:

>>> import yaml
>>> data = {'a':2, 'b':{'x':3, 'y':{'t1': 4, 't2':5}}}
>>> print(yaml.dump(data, default_flow_style=False))
a: 2
b:
  x: 3
  y:
    t1: 4
    t2: 5
Maxim
  • 6,417
  • 1
  • 27
  • 28
Andy Mikhaylenko
  • 1,329
  • 10
  • 10
  • 2
    Using yaml is very interesting because it keep data type over it's format, the only thing I can say against it is that it don't produce a valid python string, but can almost be converted back in python. – y.petremann Oct 06 '14 at 04:49
  • 2
    yaml doesn't like Numpy's version of scalar types... I wasn't surprised that is doesn't support numpy arrays, but I would have expected the same output for a `float` and a `numpy.float64` – PhilMacKay Mar 02 '17 at 17:12
  • 1
    this approach also worked for me using a list of dictionaries – Grant Shannon Feb 18 '20 at 08:18
75

By this way you can print it in pretty way for example your dictionary name is yasin

import json

print (json.dumps(yasin, indent=2))

or, safer:

print (json.dumps(yasin, indent=2, default=str))
mike rodent
  • 12,285
  • 11
  • 88
  • 123
yasin lachini
  • 3,936
  • 3
  • 23
  • 48
  • 12
    This assumes the content of the dictionary is json serialize-able, which is necessarily not true. – SpiXel Oct 07 '19 at 11:20
  • 1
    @SpiXel. I like Juan-Kabbali's answer ... but just to answer your point, one can go: `print (json.dumps(yasin, indent=2, default=str))` : anything "hairy" is then handled with the `str` function. – mike rodent Feb 10 '21 at 18:11
  • this solved my problem with "Object of type User is not JSON serializable" – SearchTools-Avi Jul 13 '21 at 01:12
49

One of the most pythonic ways for that is to use the already build pprint module.

The argument that you need for define the print depth is as you may expect depth

import pprint
pp = pprint.PrettyPrinter(depth=4)
pp.pprint(mydict)

That's it !

Juan-Kabbali
  • 1,201
  • 13
  • 19
47

As of what have been done, I don't see any pretty printer that at least mimics the output of the python interpreter with very simple formatting so here's mine :

class Formatter(object):
    def __init__(self):
        self.types = {}
        self.htchar = '\t'
        self.lfchar = '\n'
        self.indent = 0
        self.set_formater(object, self.__class__.format_object)
        self.set_formater(dict, self.__class__.format_dict)
        self.set_formater(list, self.__class__.format_list)
        self.set_formater(tuple, self.__class__.format_tuple)

    def set_formater(self, obj, callback):
        self.types[obj] = callback

    def __call__(self, value, **args):
        for key in args:
            setattr(self, key, args[key])
        formater = self.types[type(value) if type(value) in self.types else object]
        return formater(self, value, self.indent)

    def format_object(self, value, indent):
        return repr(value)

    def format_dict(self, value, indent):
        items = [
            self.lfchar + self.htchar * (indent + 1) + repr(key) + ': ' +
            (self.types[type(value[key]) if type(value[key]) in self.types else object])(self, value[key], indent + 1)
            for key in value
        ]
        return '{%s}' % (','.join(items) + self.lfchar + self.htchar * indent)

    def format_list(self, value, indent):
        items = [
            self.lfchar + self.htchar * (indent + 1) + (self.types[type(item) if type(item) in self.types else object])(self, item, indent + 1)
            for item in value
        ]
        return '[%s]' % (','.join(items) + self.lfchar + self.htchar * indent)

    def format_tuple(self, value, indent):
        items = [
            self.lfchar + self.htchar * (indent + 1) + (self.types[type(item) if type(item) in self.types else object])(self, item, indent + 1)
            for item in value
        ]
        return '(%s)' % (','.join(items) + self.lfchar + self.htchar * indent)

To initialize it :

pretty = Formatter()

It can support the addition of formatters for defined types, you simply need to make a function for that like this one and bind it to the type you want with set_formater :

from collections import OrderedDict

def format_ordereddict(self, value, indent):
    items = [
        self.lfchar + self.htchar * (indent + 1) +
        "(" + repr(key) + ', ' + (self.types[
            type(value[key]) if type(value[key]) in self.types else object
        ])(self, value[key], indent + 1) + ")"
        for key in value
    ]
    return 'OrderedDict([%s])' % (','.join(items) +
           self.lfchar + self.htchar * indent)
pretty.set_formater(OrderedDict, format_ordereddict)

For historical reasons, I keep the previous pretty printer which was a function instead of a class, but they both can be used the same way, the class version simply permit much more :

def pretty(value, htchar='\t', lfchar='\n', indent=0):
    nlch = lfchar + htchar * (indent + 1)
    if type(value) is dict:
        items = [
            nlch + repr(key) + ': ' + pretty(value[key], htchar, lfchar, indent + 1)
            for key in value
        ]
        return '{%s}' % (','.join(items) + lfchar + htchar * indent)
    elif type(value) is list:
        items = [
            nlch + pretty(item, htchar, lfchar, indent + 1)
            for item in value
        ]
        return '[%s]' % (','.join(items) + lfchar + htchar * indent)
    elif type(value) is tuple:
        items = [
            nlch + pretty(item, htchar, lfchar, indent + 1)
            for item in value
        ]
        return '(%s)' % (','.join(items) + lfchar + htchar * indent)
    else:
        return repr(value)

To use it :

>>> a = {'list':['a','b',1,2],'dict':{'a':1,2:'b'},'tuple':('a','b',1,2),'function':pretty,'unicode':u'\xa7',("tuple","key"):"valid"}
>>> a
{'function': <function pretty at 0x7fdf555809b0>, 'tuple': ('a', 'b', 1, 2), 'list': ['a', 'b', 1, 2], 'dict': {'a': 1, 2: 'b'}, 'unicode': u'\xa7', ('tuple', 'key'): 'valid'}
>>> print(pretty(a))
{
    'function': <function pretty at 0x7fdf555809b0>,
    'tuple': (
        'a',
        'b',
        1,
        2
    ),
    'list': [
        'a',
        'b',
        1,
        2
    ],
    'dict': {
        'a': 1,
        2: 'b'
    },
    'unicode': u'\xa7',
    ('tuple', 'key'): 'valid'
}

Compared to other versions :

  • This solution looks directly for object type, so you can pretty print almost everything, not only list or dict.
  • Doesn't have any dependancy.
  • Everything is put inside a string, so you can do whatever you want with it.
  • The class and the function has been tested and works with Python 2.7 and 3.4.
  • You can have all type of objects inside, this is their representations and not theirs contents that being put in the result (so string have quotes, Unicode string are fully represented ...).
  • With the class version, you can add formatting for every object type you want or change them for already defined ones.
  • key can be of any valid type.
  • Indent and Newline character can be changed for everything we'd like.
  • Dict, List and Tuples are pretty printed.
y.petremann
  • 2,512
  • 1
  • 14
  • 15
18

I had to pass the default parameter as well, like this:

print(json.dumps(my_dictionary, indent=4, default=str))

and if you want the keys sorted, then you can do:

print(json.dumps(my_dictionary, sort_keys=True, indent=4, default=str))

in order to fix this type error:

TypeError: Object of type 'datetime' is not JSON serializable

which caused by datetimes being some values in the dictionary.

gsamaras
  • 69,751
  • 39
  • 173
  • 279
14

Another option with yapf:

from pprint import pformat
from yapf.yapflib.yapf_api import FormatCode

dict_example = {'1': '1', '2': '2', '3': [1, 2, 3, 4, 5], '4': {'1': '1', '2': '2', '3': [1, 2, 3, 4, 5]}}
dict_string = pformat(dict_example)
formatted_code, _ = FormatCode(dict_string)

print(formatted_code)

Output:

{
    '1': '1',
    '2': '2',
    '3': [1, 2, 3, 4, 5],
    '4': {
        '1': '1',
        '2': '2',
        '3': [1, 2, 3, 4, 5]
    }
}
Eyal Levin
  • 13,555
  • 5
  • 61
  • 54
  • This solution assumes that `yapf` installed by default, which is not. you can install it `pip install yapf`. If you are using conda `conda install yapf` – Medhat Oct 05 '20 at 22:12
  • Very useful when you have non JSON keys in your dictionary, like tuples. – Danilo Gómez Mar 23 '21 at 13:50
  • Why use `pformat` to serialize a dictionary when you can use `repr`? Since `yafp` is actually the formatter, and it only needs a string. – Danilo Gómez Mar 23 '21 at 13:52
10

The modern solution here is to use rich. Install with

pip install rich

and use as

from rich import print

d = {
    "Alabama": "Montgomery",
    "Alaska": "Juneau",
    "Arizona": "Phoenix",
    "Arkansas": "Little Rock",
    "California": "Sacramento",
    "Colorado": "Denver",
    "Connecticut": "Hartford",
    "Delaware": "Dover",
    "Florida": "Tallahassee",
    "Georgia": "Atlanta",
    "Hawaii": "Honolulu",
    "Idaho": "Boise",
}
print(d)

The output is nicely indented:

enter image description here

Nico Schlömer
  • 46,467
  • 24
  • 178
  • 218
  • Tried a few different things with pprint and json.dumps that didn't work out but this worked great! – Christian Wilkie Oct 10 '21 at 19:47
  • Unless I am missing something, this is good *only* if you want to print to console, but not if logging to a log file since it's whole function is to *print*. Would be nice if this lib actually returned a value that could be used. – Eitel Dagnin Mar 11 '22 at 10:34
  • The documentation for Rich { https://github.com/Textualize/rich#rich-print } says that it will work with terminals and Jupyter Notebooks too. @EitelDagnin you are asking for a formatter, not just a "pretty printer" like the OP asked for. – Rich Lysakowski PhD Apr 22 '22 at 11:22
7

You can use print-dict

from print_dict import pd

dict1 = {
    'key': 'value'
} 

pd(dict1)

Output:

{
    'key': 'value'
}

Output of this Python code:

{
    'one': 'value-one',
    'two': 'value-two',
    'three': 'value-three',
    'four': {
        '1': '1',
        '2': '2',
        '3': [1, 2, 3, 4, 5],
        '4': {
            'method': <function custom_method at 0x7ff6ecd03e18>,
            'tuple': (1, 2),
            'unicode': '✓',
            'ten': 'value-ten',
            'eleven': 'value-eleven',
            '3': [1, 2, 3, 4]
        }
    },
    'object1': <__main__.Object1 object at 0x7ff6ecc588d0>,
    'object2': <Object2 info>,
    'class': <class '__main__.Object1'>
}

Install:

$ pip install print-dict

Disclosure: I'm the author of print-dict

Eyal Levin
  • 13,555
  • 5
  • 61
  • 54
  • 2
    This is the easiest solution. Works great for large dictionaries with a lot of nested keys. – Nairum Aug 24 '20 at 14:43
6

As others have posted, you can use recursion/dfs to print the nested dictionary data and call recursively if it is a dictionary; otherwise print the data.

def print_json(data):
    if type(data) == dict:
            for k, v in data.items():
                    print k
                    print_json(v)
    else:
            print data
Brad Solomon
  • 34,372
  • 28
  • 129
  • 206
5

pout can pretty print anything you throw at it, for example (borrowing data from another answer):

data = {'a':2, 'b':{'x':3, 'y':{'t1': 4, 't2':5}}}
pout.vs(data)

would result in output printed to the screen like:

{
    'a': 2,
    'b':
    {
        'y':
        {
            't2': 5,
            't1': 4
        },
        'x': 3
    }
}

or you can return the formatted string output of your object:

v = pout.s(data)

Its primary use case is for debugging so it doesn't choke on object instances or anything and it handles unicode output as you would expect, works in python 2.7 and 3.

disclosure: I'm the author and maintainer of pout.

Jaymon
  • 4,658
  • 2
  • 31
  • 32
  • Doesn't work on windows unfortunately, would be nice if you showed supported systems clearly – Mandera Nov 11 '20 at 17:24
  • @Mandera If you could open an issue at https://github.com/Jaymon/pout/issues with details since I can't think of any reason why it wouldn't work on Windows, we can continue the conversation there – Jaymon Nov 11 '20 at 23:09
  • Oh sure thing! My mistake assuming you weren't trying to support it – Mandera Nov 12 '20 at 06:35
4

I took sth's answer and modified it slightly to fit my needs of a nested dictionaries and lists:

def pretty(d, indent=0):
    if isinstance(d, dict):
        for key, value in d.iteritems():
            print '\t' * indent + str(key)
            if isinstance(value, dict) or isinstance(value, list):
                pretty(value, indent+1)
            else:
                print '\t' * (indent+1) + str(value)
    elif isinstance(d, list):
        for item in d:
            if isinstance(item, dict) or isinstance(item, list):
                pretty(item, indent+1)
            else:
                print '\t' * (indent+1) + str(item)
    else:
        pass

Which then gives me output like:

>>> 
xs:schema
    @xmlns:xs
        http://www.w3.org/2001/XMLSchema
    xs:redefine
        @schemaLocation
            base.xsd
        xs:complexType
            @name
                Extension
            xs:complexContent
                xs:restriction
                    @base
                        Extension
                    xs:sequence
                        xs:element
                            @name
                                Policy
                            @minOccurs
                                1
                            xs:complexType
                                xs:sequence
                                    xs:element
                                            ...
Community
  • 1
  • 1
Jamie Ivanov
  • 1,022
  • 7
  • 11
3

I used what you guys taught me plus the power of decorators to overload the classic print function. Just change the indent to your needs. I added it as a gist in github in case you want to star(save) it.

def print_decorator(func):
    """
    Overload Print function to pretty print Dictionaries 
    """
    def wrapped_func(*args,**kwargs):
        if isinstance(*args, dict):
            return func(json.dumps(*args, sort_keys=True, indent=2, default=str))
        else:
            return func(*args,**kwargs)
    return wrapped_func
print = print_decorator(print)

Now just use print as usual.

2

I wrote this simple code to print the general structure of a json object in Python.

def getstructure(data, tab = 0):
    if type(data) is dict:
        print ' '*tab + '{' 
        for key in data:
            print ' '*tab + '  ' + key + ':'
            getstructure(data[key], tab+4)
        print ' '*tab + '}'         
    elif type(data) is list and len(data) > 0:
        print ' '*tab + '['
        getstructure(data[0], tab+4)
        print ' '*tab + '  ...'
        print ' '*tab + ']'

the result for the following data

a = {'list':['a','b',1,2],'dict':{'a':1,2:'b'},'tuple':('a','b',1,2),'function':'p','unicode':u'\xa7',("tuple","key"):"valid"}
getstructure(a)

is very compact and looks like this:

{
  function:
  tuple:
  list:
    [
      ...
    ]
  dict:
    {
      a:
      2:
    }
  unicode:
  ('tuple', 'key'):
}
Abtin Rasoulian
  • 749
  • 1
  • 7
  • 11
2

I tried the following and got my desired results

Method 1: Step 1: Install print_dict by typing the following command in cmd

pip install print_dict

Step 2: Import print_dict as

from print_dict import pd

Step 3: Printing using pd

pd(your_dictionary_name)

Example Output:

{
    'Name': 'Arham Rumi',
    'Age': 21,
    'Movies': ['adas', 'adfas', 'fgfg', 'gfgf', 'vbxbv'],
    'Songs': ['sdfsd', 'dfdgfddf', 'dsdfd', 'sddfsd', 'sdfdsdf']
}

Method 2: We can also use for loop to print the dictionary using items method

for key, Value in your_dictionary_name.items():
    print(f"{key} : {Value}")
ARHAM RUMI
  • 195
  • 1
  • 8
  • Method 2 here is one of the best I have seen on this SO post, because it is core Python 3 only, no JSON imports. With a little bit of dynamic formatting, this could print nice-looking tabular nested outputs. – Rich Lysakowski PhD Apr 22 '22 at 11:01
1

Sth, i sink that's pretty ;)

def pretty(d, indent=0):
    for key, value in d.iteritems():
        if isinstance(value, dict):
            print '\t' * indent + (("%30s: {\n") % str(key).upper())
            pretty(value, indent+1)
            print '\t' * indent + ' ' * 32 + ('} # end of %s #\n' % str(key).upper())
        elif isinstance(value, list):
            for val in value:
                print '\t' * indent + (("%30s: [\n") % str(key).upper())
                pretty(val, indent+1)
                print '\t' * indent + ' ' * 32 + ('] # end of %s #\n' % str(key).upper())
        else:
            print '\t' * indent + (("%30s: %s") % (str(key).upper(),str(value)))
VindeX
  • 35
  • 2
  • 2
    -1: Doesn't handle `list` values that aren't `dict` instances, i.e. `pretty({'key': [1, 2, 3]}, indent=4)` ==> `AttributeError: 'int' object has no attribute 'iteritems'`. I also don't like it uppercasing keys. – martineau May 24 '13 at 02:36
  • Your solution consider that there can't be a dict inside a list inside the root dict. Also it consider that we don't want to prettyprint a list or a tuple. Finally don't capitalize keys, the result for {'a':0,'A':1} would not be correct. – y.petremann Nov 22 '14 at 11:07
1
This class prints out a complex nested dictionary with sub dictionaries and sub lists.  
##
## Recursive class to parse and print complex nested dictionary
##

class NestedDictionary(object):
    def __init__(self,value):
        self.value=value

    def print(self,depth):
        spacer="--------------------"
        if type(self.value)==type(dict()):
            for kk, vv in self.value.items():
                if (type(vv)==type(dict())):
                    print(spacer[:depth],kk)
                    vvv=(NestedDictionary(vv))
                    depth=depth+3
                    vvv.print(depth)
                    depth=depth-3
                else:
                    if (type(vv)==type(list())):
                        for i in vv:
                            vvv=(NestedDictionary(i))
                            depth=depth+3
                            vvv.print(depth)
                            depth=depth-3
                    else:
                        print(spacer[:depth],kk,vv) 

##
## Instatiate and execute - this prints complex nested dictionaries
## with sub dictionaries and sub lists
## 'something' is a complex nested dictionary

MyNest=NestedDictionary(weather_com_result)
MyNest.print(0)
Derek Adair
  • 21,351
  • 31
  • 94
  • 133
1

I'm just returning to this question after taking sth's answer and making a small but very useful modification. This function prints all keys in the JSON tree as well as the size of leaf nodes in that tree.

def print_JSON_tree(d, indent=0):
    for key, value in d.iteritems():
        print '    ' * indent + unicode(key),
        if isinstance(value, dict):
            print; print_JSON_tree(value, indent+1)
        else:
            print ":", str(type(d[key])).split("'")[1], "-", str(len(unicode(d[key])))

It's really nice when you have large JSON objects and want to figure out where the meat is. Example:

>>> print_JSON_tree(JSON_object)
key1
    value1 : int - 5
    value2 : str - 16
    key2
       value1 : str - 34
       value2 : list - 5623456

This would tell you that most of the data you care about is probably inside JSON_object['key1']['key2']['value2'] because the length of that value formatted as a string is very large.

Ulf Aslak
  • 6,938
  • 3
  • 32
  • 55
1

The easiest is to install IPython and use something like below

from IPython.lib.pretty import pretty


class MyClass:
    __repr__(self):
       return pretty(data)  # replace data with what makes sense

In your case

print(pretty(mydict))
Pithikos
  • 16,954
  • 15
  • 107
  • 126
0

Here's a function I wrote based on what sth's comment. It's works the same as json.dumps with indent, but I'm using tabs instead of space for indents. In Python 3.2+ you can specify indent to be a '\t' directly, but not in 2.7.

def pretty_dict(d):
    def pretty(d, indent):
        for i, (key, value) in enumerate(d.iteritems()):
            if isinstance(value, dict):
                print '{0}"{1}": {{'.format( '\t' * indent, str(key))
                pretty(value, indent+1)
                if i == len(d)-1:
                    print '{0}}}'.format( '\t' * indent)
                else:
                    print '{0}}},'.format( '\t' * indent)
            else:
                if i == len(d)-1:
                    print '{0}"{1}": "{2}"'.format( '\t' * indent, str(key), value)
                else:
                    print '{0}"{1}": "{2}",'.format( '\t' * indent, str(key), value)
    print '{'
    pretty(d,indent=1)
    print '}'

Ex:

>>> dict_var = {'a':2, 'b':{'x':3, 'y':{'t1': 4, 't2':5}}}
>>> pretty_dict(dict_var)
{
    "a": "2",
    "b": {
        "y": {
            "t2": "5",
            "t1": "4"
        },
        "x": "3"
    }
}
Al Conrad
  • 1,320
  • 15
  • 11
  • I can't make it works with the nested dict of my solution, because it gave me a UnicodeEncodeError, also items and keys are all converted in strings, what if we use numbers or tuples that contains lists and dicts ? Finnaly your solution take in account that our object we want to pretty print must be a dict. – y.petremann Oct 06 '14 at 04:26
  • I was not trying to write a generic print function for a python dict. The top rated comments already demonstrate how to pretty print a dict. My contribution was to write an alternative to json.dumps with '\t' for indenting instead of tabs in python 2.7. – Al Conrad Oct 08 '14 at 18:47
  • I agree with you about writing an alternative to json.dumps, for me the same problems as of json.dumps applies. Also, you could use a simple regex to change the indentation type, making your code simplier. – y.petremann Oct 08 '14 at 21:46
0

From this link:

def prnDict(aDict, br='\n', html=0,
            keyAlign='l',   sortKey=0,
            keyPrefix='',   keySuffix='',
            valuePrefix='', valueSuffix='',
            leftMargin=0,   indent=1 ):
    '''
return a string representive of aDict in the following format:
    {
     key1: value1,
     key2: value2,
     ...
     }

Spaces will be added to the keys to make them have same width.

sortKey: set to 1 if want keys sorted;
keyAlign: either 'l' or 'r', for left, right align, respectively.
keyPrefix, keySuffix, valuePrefix, valueSuffix: The prefix and
   suffix to wrap the keys or values. Good for formatting them
   for html document(for example, keyPrefix='<b>', keySuffix='</b>'). 
   Note: The keys will be padded with spaces to have them
         equally-wide. The pre- and suffix will be added OUTSIDE
         the entire width.
html: if set to 1, all spaces will be replaced with '&nbsp;', and
      the entire output will be wrapped with '<code>' and '</code>'.
br: determine the carriage return. If html, it is suggested to set
    br to '<br>'. If you want the html source code eazy to read,
    set br to '<br>\n'

version: 04b52
author : Runsun Pan
require: odict() # an ordered dict, if you want the keys sorted.
         Dave Benjamin 
         http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/161403
    '''

    if aDict:

        #------------------------------ sort key
        if sortKey:
            dic = aDict.copy()
            keys = dic.keys()
            keys.sort()
            aDict = odict()
            for k in keys:
                aDict[k] = dic[k]

        #------------------- wrap keys with ' ' (quotes) if str
        tmp = ['{']
        ks = [type(x)==str and "'%s'"%x or x for x in aDict.keys()]

        #------------------- wrap values with ' ' (quotes) if str
        vs = [type(x)==str and "'%s'"%x or x for x in aDict.values()] 

        maxKeyLen = max([len(str(x)) for x in ks])

        for i in range(len(ks)):

            #-------------------------- Adjust key width
            k = {1            : str(ks[i]).ljust(maxKeyLen),
                 keyAlign=='r': str(ks[i]).rjust(maxKeyLen) }[1]

            v = vs[i]        
            tmp.append(' '* indent+ '%s%s%s:%s%s%s,' %(
                        keyPrefix, k, keySuffix,
                        valuePrefix,v,valueSuffix))

        tmp[-1] = tmp[-1][:-1] # remove the ',' in the last item
        tmp.append('}')

        if leftMargin:
          tmp = [ ' '*leftMargin + x for x in tmp ]

        if html:
            return '<code>%s</code>' %br.join(tmp).replace(' ','&nbsp;')
        else:
            return br.join(tmp)     
    else:
        return '{}'

'''
Example:

>>> a={'C': 2, 'B': 1, 'E': 4, (3, 5): 0}

>>> print prnDict(a)
{
 'C'   :2,
 'B'   :1,
 'E'   :4,
 (3, 5):0
}

>>> print prnDict(a, sortKey=1)
{
 'B'   :1,
 'C'   :2,
 'E'   :4,
 (3, 5):0
}

>>> print prnDict(a, keyPrefix="<b>", keySuffix="</b>")
{
 <b>'C'   </b>:2,
 <b>'B'   </b>:1,
 <b>'E'   </b>:4,
 <b>(3, 5)</b>:0
}

>>> print prnDict(a, html=1)
<code>{
&nbsp;'C'&nbsp;&nbsp;&nbsp;:2,
&nbsp;'B'&nbsp;&nbsp;&nbsp;:1,
&nbsp;'E'&nbsp;&nbsp;&nbsp;:4,
&nbsp;(3,&nbsp;5):0
}</code>

>>> b={'car': [6, 6, 12], 'about': [15, 9, 6], 'bookKeeper': [9, 9, 15]}

>>> print prnDict(b, sortKey=1)
{
 'about'     :[15, 9, 6],
 'bookKeeper':[9, 9, 15],
 'car'       :[6, 6, 12]
}

>>> print prnDict(b, keyAlign="r")
{
        'car':[6, 6, 12],
      'about':[15, 9, 6],
 'bookKeeper':[9, 9, 15]
}
'''
Nathaniel Ford
  • 18,661
  • 20
  • 81
  • 93
user2757572
  • 433
  • 1
  • 4
  • 9
0

I'm a relative python newbie myself but I've been working with nested dictionaries for the past couple weeks and this is what I had came up with.

You should try using a stack. Make the keys from the root dictionary into a list of a list:

stack = [ root.keys() ]     # Result: [ [root keys] ]

Going in reverse order from last to first, lookup each key in the dictionary to see if its value is (also) a dictionary. If not, print the key then delete it. However if the value for the key is a dictionary, print the key then append the keys for that value to the end of the stack, and start processing that list in the same way, repeating recursively for each new list of keys.

If the value for the second key in each list were a dictionary you would have something like this after several rounds:

[['key 1','key 2'],['key 2.1','key 2.2'],['key 2.2.1','key 2.2.2'],[`etc.`]]

The upside to this approach is that the indent is just \t times the length of the stack:

indent = "\t" * len(stack)

The downside is that in order to check each key you need to hash through to the relevant sub-dictionary, though this can be handled easily with a list comprehension and a simple for loop:

path = [li[-1] for li in stack]
# The last key of every list of keys in the stack

sub = root
for p in path:
    sub = sub[p]


if type(sub) == dict:
    stack.append(sub.keys()) # And so on

Be aware that this approach will require you to cleanup trailing empty lists, and to delete the last key in any list followed by an empty list (which of course may create another empty list, and so on).

There are other ways to implement this approach but hopefully this gives you a basic idea of how to do it.

EDIT: If you don't want to go through all that, the pprint module prints nested dictionaries in a nice format.

danwroy
  • 47
  • 6
0

Here's something that will print any sort of nested dictionary, while keeping track of the "parent" dictionaries along the way.

dicList = list()

def prettierPrint(dic, dicList):
count = 0
for key, value in dic.iteritems():
    count+=1
    if str(value) == 'OrderedDict()':
        value = None
    if not isinstance(value, dict):
        print str(key) + ": " + str(value)
        print str(key) + ' was found in the following path:',
        print dicList
        print '\n'
    elif isinstance(value, dict):
        dicList.append(key)
        prettierPrint(value, dicList)
    if dicList:
         if count == len(dic):
             dicList.pop()
             count = 0

prettierPrint(dicExample, dicList)

This is a good starting point for printing according to different formats, like the one specified in OP. All you really need to do is operations around the Print blocks. Note that it looks to see if the value is 'OrderedDict()'. Depending on whether you're using something from Container datatypes Collections, you should make these sort of fail-safes so the elif block doesn't see it as an additional dictionary due to its name. As of now, an example dictionary like

example_dict = {'key1': 'value1',
            'key2': 'value2',
            'key3': {'key3a': 'value3a'},
            'key4': {'key4a': {'key4aa': 'value4aa',
                               'key4ab': 'value4ab',
                               'key4ac': 'value4ac'},
                     'key4b': 'value4b'}

will print

key3a: value3a
key3a was found in the following path: ['key3']

key2: value2
key2 was found in the following path: []

key1: value1
key1 was found in the following path: []

key4ab: value4ab
key4ab was found in the following path: ['key4', 'key4a']

key4ac: value4ac
key4ac was found in the following path: ['key4', 'key4a']

key4aa: value4aa
key4aa was found in the following path: ['key4', 'key4a']

key4b: value4b
key4b was found in the following path: ['key4']

~altering code to fit the question's format~

lastDict = list()
dicList = list()
def prettierPrint(dic, dicList):
    global lastDict
    count = 0
    for key, value in dic.iteritems():
        count+=1
        if str(value) == 'OrderedDict()':
            value = None
        if not isinstance(value, dict):
            if lastDict == dicList:
                sameParents = True
            else:
                sameParents = False

            if dicList and sameParents is not True:
                spacing = ' ' * len(str(dicList))
                print dicList
                print spacing,
                print str(value)

            if dicList and sameParents is True:
                print spacing,
                print str(value)
            lastDict = list(dicList)

        elif isinstance(value, dict):
            dicList.append(key)
            prettierPrint(value, dicList)

        if dicList:
             if count == len(dic):
                 dicList.pop()
                 count = 0

Using the same example code, it will print the following:

['key3']
         value3a
['key4', 'key4a']
                  value4ab
                  value4ac
                  value4aa
['key4']
         value4b

This isn't exactly what is requested in OP. The difference is that a parent^n is still printed, instead of being absent and replaced with white-space. To get to OP's format, you'll need to do something like the following: iteratively compare dicList with the lastDict. You can do this by making a new dictionary and copying dicList's content to it, checking if i in the copied dictionary is the same as i in lastDict, and -- if it is -- writing whitespace to that i position using the string multiplier function.

gavin
  • 41
  • 1
  • 3
0

Use this function:

def pretty_dict(d, n=1):
    for k in d:
        print(" "*n + k)
        try:
            pretty_dict(d[k], n=n+4)
        except TypeError:
            continue

Call it like this:

pretty_dict(mydict)
fiftytwocards
  • 77
  • 1
  • 5
  • This doesn't work if the values are strings. It prints each character of the string on a new line, but the keys seem to work okay. – Anthony Feb 09 '20 at 17:52
0

This is what I came up with while working on a class that needed to write a dictionary in a .txt file:

@staticmethod
def _pretty_write_dict(dictionary):

    def _nested(obj, level=1):
        indentation_values = "\t" * level
        indentation_braces = "\t" * (level - 1)
        if isinstance(obj, dict):
            return "{\n%(body)s%(indent_braces)s}" % {
                "body": "".join("%(indent_values)s\'%(key)s\': %(value)s,\n" % {
                    "key": str(key),
                    "value": _nested(value, level + 1),
                    "indent_values": indentation_values
                } for key, value in obj.items()),
                "indent_braces": indentation_braces
            }
        if isinstance(obj, list):
            return "[\n%(body)s\n%(indent_braces)s]" % {
                "body": "".join("%(indent_values)s%(value)s,\n" % {
                    "value": _nested(value, level + 1),
                    "indent_values": indentation_values
                } for value in obj),
                "indent_braces": indentation_braces
            }
        else:
            return "\'%(value)s\'" % {"value": str(obj)}

    dict_text = _nested(dictionary)
    return dict_text

Now, if we have a dictionary like this:

some_dict = {'default': {'ENGINE': [1, 2, 3, {'some_key': {'some_other_key': 'some_value'}}], 'NAME': 'some_db_name', 'PORT': '', 'HOST': 'localhost', 'USER': 'some_user_name', 'PASSWORD': 'some_password', 'OPTIONS': {'init_command': 'SET foreign_key_checks = 0;'}}}

And we do:

print(_pretty_write_dict(some_dict))

We get:

{
    'default': {
        'ENGINE': [
            '1',
            '2',
            '3',
            {
                'some_key': {
                    'some_other_key': 'some_value',
                },
            },
        ],
        'NAME': 'some_db_name',
        'OPTIONS': {
            'init_command': 'SET foreign_key_checks = 0;',
        },
        'HOST': 'localhost',
        'USER': 'some_user_name',
        'PASSWORD': 'some_password',
        'PORT': '',
    },
}