License New BSD license
Lines 50
Keywords
dictionary (1) introspection (1) pretty (3) pretty print (3) print (6) python (33) tree (2)
Permissions
Owner: Theodore Test
Viewable by Everyone
Editable by All Siafoo Users
Hide
Siafoo is here to make coding less frustrating and to save you time. Join Siafoo Now or Learn More

Robust Mixed-Type Dictionary Tree Printer Atom Feed 0

In Brief A robust way to print out (or produce strings for printing out) a dictionary of arbitrary objects in an easily-readable tree format. I was inspired to put this up by Andrew Stromberg's Dictionary Printer .... more
# 's
 1def dict_printer(a_dict,string_so_far='',depth_index=0,print_it=True):
2 '''Takes a dictionary and prints the contents in a tree format.
3
4 Returns a formatted string of the contents for later parsing/printing/use.
5
6 As long as each of the contents have a __str__ method, this should work
7 on any sort of dictionary whatsoever.
8
9 The string_so_far and depth_index arguments are intended for internal use,
10 most users can ignore them.'''
11
12
13 if not hasattr(a_dict,'iteritems'):
14 return ''
15
16 local_string = string_so_far
17 spacer = '\n' + '\t'*depth_index
18
19 for item in a_dict.iteritems():
20
21 # We want to be extra certain that iteritems is spitting out proper tuples
22 # Really only an issue if someone has passed an object with a non-dict-style
23 # iteritems method.
24 try:
25 assert len(item) >= 2
26 except (AssertionError,TypeError):
27 print "Error produced by a dictionary-produced iteritem item. Returning string_so_far."
28 return local_string
29
30 k = item[0]
31 v = item[1]
32
33 if hasattr(v,'iteritems'):
34 local_string += spacer + str(k) + ':'
35 local_string += dict_printer(v,string_so_far,depth_index = depth_index+1)
36 else:
37 local_string += spacer + str(k) + ': ' + str(v)
38
39
40 if depth_index == 0 and print_it:
41 print local_string
42 return local_string
43
44
45if __name__ == '__main__':
46 c = {'a':1,'b':{'d':2,'c':{'why go deeper?':"because we can",
47 1000:"e",'d':3},
48 'a2':{'a':'you might notice that it does not particularly sort the items',
49 'b':'this is to avoid errors from funkily-implemented on key-object comparison methods'},
50 'a_list':['look','ma','semi-arbitrary','types are printable']}}
51
52 full_out = dict_printer(c)
53
54 suppressed_print = dict_printer(c,print_it=False)

A robust way to print out (or produce strings for printing out) a dictionary of arbitrary objects in an easily-readable tree format. I was inspired to put this up by Andrew Stromberg's Dictionary Printer .

This version should be a little safer for inspecting dictionaries where you can't vouch for the contents' formatting or types a priori.

Example Output

a: 1
b:
        c:
                1000: e
                why go deeper?: because we can
                d: 3
        a2:
                a: you might notice that it does not particularly sort the items
                b: this is to avoid errors from funkily-implemented on key-object comparison methods
        a_list: ['look', 'ma', 'semi-arbitrary', 'types are printable']
        d: 2