Iterating Through Dictionary of Lists

JB jamesb7us at gmail.com
Mon Sep 14 13:48:08 EDT 2009


On Sep 11, 9:42 am, Stefan Behnel <stefan... at behnel.de> wrote:
> JBwrote:
> > I have created a small program that generates a project tree from a
> > dictionary. The dictionary is of key/value pairs where each key is a
> > directory, and each value is a list. The list have unique values
> > corresponding to the key, which is a directory where each value in the
> > list becomes a subdirectory.
>
> > The question that I have is how to do this process if one of the
> > unique values in the list is itself a dict. For example, in the
> > "projdir" dict below, suppose the "Analysis" value in the list
> > corresponding to the "Engineering" key was itself a dict and was
> > assigned {'Analysis' : 'Simulink'} for example.
>
> You might want to read up on recursion, i.e. a function calling itself.
>
> You can find out if something is a dict like this:
>
>         isinstance(x, dict)
>
> or, if you know it really is a dict and not a subtype:
>
>         type(x) is dict
>
> Stefan

Stefan;

Thanks for your valuable suggestion. I have employed your suggestion
with the code below.
I also converted this to object oriented design. With this type of
construction, the
program will easily handle the dictionary specified by the self.proj
variable. This
variable is a dictionary with some of the value variables also being
dictionaries.
I did not generalize the function call but have more of horizontal
code for this
area of the implementation. If this program were packaged with a GUI,
it would
make the beginning of a project management software platform.

-James



from time import strftime
import os

#-------------------------------------
# Print/Make Directories
#-------------------------------------
class Tree:
 def __init__(self,dir_main,dir_sub,sch_names,drawing_name):
	self.proj         =     {'Project'        :  ['Schedule',
'Specifications'],

            'Schematics_PCB' :  [{'SCH':sch_names},{'BOM':sch_names},
{'ASSY':sch_names},
                                 {'RELEASE':sch_names}],

            'Drawings'       :  [{'System':drawing_name},
{'Board':sch_names},
                                 'Packaging_3D'],

            'Engineering'    :  [{'Analysis':
['Simulink','Matlab','Excel',
                                              'MathCad','Python']},
                                 {'Eng Reports':sch_names}, {'Design
Reviews':sch_names},
                                 {'Procedures':['Board Test','System
Test']}]}
	self.sch_names    = sch_names
	self.drawing_name = drawing_name
	self.dir_main     = dir_main
	self.dir_sub      = dir_sub
	self.root         = self.dir_main + self.dir_sub
	self.pathname     = ''
	self.suffix       = "\\Previous \n"
	self.recursion    = 0.0
	self.zs           = ''

 def gen_dir(self):
	if os.path.exists(self.pathname):
		pass
	else:
		os.makedirs(self.pathname)
	return

 def print_path(self):
	print self.pathname
	Tree.gen_dir(self)

	self.zs = self.pathname + self.suffix

	Tree.gen_dir(self)
	print self.zs
#-------------------------------------
# Make a Directory Project Tree
#-------------------------------------
 def make_tree(self):
	counter = 0
	print "This project tree for " + self.dir_sub[0:-1] + " was completed
by "
	print "Generated on " + strftime("%m/%d/%Y at %H.%M hours")
	print "The project tree / dictionary was found to have the following:
\n"
	
#-------------------------------------------------------------------------
	# Iterate over items in the dictionary, creating tuples of key/value
pairs
	
#-------------------------------------------------------------------------
	for key, values in self.proj.iteritems():
		counter = counter + 1
		print "Key #" + str(counter) + " is "  + "'" + key + "\\"
		print "For this key, the values are " + str(values)
		print "Thus, the results of generating directories for this "
		print " key/values combo are: \n"
		#---------------------------------------------------------
		# Iterate over the invidividual unique values in the list
		# that is associated with each key in the dict, where
		# an individual value may itself be a dict
		#---------------------------------------------------------
		for unique in values:
			prefix = self.root + key +  "/"
			if isinstance(unique, dict) == True:
				for kx,vx in unique.iteritems():
					if isinstance(vx,list) == True:
						for items in vx:
						  self.pathname = prefix  + kx +  "\\" + items
						  Tree.print_path(self)
					else:
					  self.pathname = prefix  + kx +  "\\" + vx
					  Tree.print_path(self)
			else:
					self.pathname = prefix + unique
					Tree.print_path(self)



if __name__== "__main__":
	#-------------------------------------
	# DEFINE Root Dir & Path, Sch Numbers
	#-------------------------------------
	sch_names     =  ['AD501','AD502','AD503']
	drawing_name  =  'AD601'
	dir_main      =  '\\\MAIN\\PUBLIC\\ABC\\TEST\\'
	dir_sub       =  "MDX\\"
	rootdir       =  dir_main + dir_sub
	#-------------------------------------
	# DEFINE Directory Tree for Project
	#-------------------------------------


	t = Tree(dir_main,dir_sub,sch_names,drawing_name)

	t.make_tree()



More information about the Python-list mailing list