Login

TreePrint: Print nested lists, tuples, dicts

Author:
michaeljtbrooks
Posted:
June 19, 2012
Language:
Python
Version:
Not specified
Score:
0 (after 0 ratings)

Displays nested lists / dicts / tuples in an aligned hierarchy to make debugging easy. Accepts all variable types, including nested lists with any mixture of tuples / dictionaries / lists / numbers / strings.

Analogous to the PHP print_r($var) function.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
########################################################################
#                   ONLEY GROUP - www.onleygroup.com                   #
#                    "Give Something Back Project"                     #
#                      (useful code we give away)                      #
#                                                                      #
#  Copyright (c) 2012, Onley Group - [email protected]  #
#                                                                      #
# Onley Free License (OFL):                                            #
# Permission to use, copy, modify, and/or distribute this software for #
# any purpose with or without fee is hereby granted, provided that the #
# above copyright notice and this permission notice appear in all      #
# copies and derivative works.                                         #
#                                                                      #
# You CAN sell this software. You CAN use this software in proprietary #
# closed-source products.                                              #
#                                                                      #
# THE SOFTWARE IS PROVIDED "AS IS" AND ONLEY GROUP DISCLAIMS ALL       #
# WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED        #
# WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ONLEY   #
# GROUP BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL  #
# DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA   #
# OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER    #
# TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR     #
# PERFORMANCE OF THIS SOFTWARE.                                        #
# ---------------------------------------------------------------------#
# Title: TreePrint                                                     #
# Language: Python                                                     #
# Type: Function(s)                                                    #
# Description:                                                         #
# Displays nested lists / dicts / tuples in an aligned hierarchy to    #
# make debugging loops easy. Accepts all variable types, inc mixed.    #
# Usage:                                                               #
#     >>> treeprint(varname)                                           #
########################################################################

def tree(var, level=1, outstr=''):
	#Takes a var, prints it out as nested aligned list
	if var is None:
		#Just return a new line:
		outstr+=' \n'
	elif isinstance(var, (int, float, long, complex, str, bool, unicode)):
		#Single value, simply add the fucker
		outstr+=' '+str(var)
		outstr+=' \n'
	elif isinstance(var, (list, tuple)):
		#List with some specified order, print in order
		outstr+='\n'
		k=0	#Manually index this
		for valchild in var:
			for tab in range(level-1):	# Print key
				outstr+='\t'
			outstr+='['+str(k)+'] => '
			k+=1	#Increment index
			newlevel = level + 1
			outstr = tree(valchild,newlevel,outstr)
	elif isinstance(var,(dict)):
		#List with keys and values, no order
		outstr+='\n'
		for k,valchild in sorted(var.iteritems()):
			for tab in range(level-1):	# Print key
				outstr+='\t'
			outstr+='['+str(k)+'] => '
			newlevel = level + 1
			outstr = tree(valchild,newlevel,outstr)
	else:
		#It doesn't qualify as any of the above cases
		outstr+=' '+str(var)
		outstr+=' \n'
	return outstr

def treeprint(var):
	#Wrapper for tree
	outstr = tree(var)
	print outstr
	return outstr	#Available to caller for wider use

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

tinti (on June 19, 2012):

didn't test this snippet, but isn't pprint not enough and standard solution in python 2.7?

from pprint import pprint<br /> pprint(list)

#

michaeljtbrooks (on June 20, 2012):

pprint doesn't do hierarchical alignment very well and makes a hash of variables that contain mixtures of lists, tuples etc. This snippet aims to make it really easy to see how such variables are structured and the values they contain.

#

Please login first before commenting.