Iterating Through Dictionary of Lists

JB jamesb7us at gmail.com
Fri Sep 11 09:32:07 EDT 2009


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.

Thanks.
James


#-------------------------------------
# DEFINE Root Dir & Path, Sch Numbers
#-------------------------------------
sch_names = ['AED500','AED600']
dir_main  = "Z:\\ABC_PROJ\\"
dir_sub   = "PCB_MDX\\"
rootdir   = dir_main + dir_sub
#-------------------------------------
# DEFINE Directory Tree for Project
#-------------------------------------
projdir =  {'Project'        :  ['Schedule', 'Specifications',
'Procedures'],
	    'Schematics_PCB' :  ['SCH','BOM','ASSY'],
	    'Drawings'       :  ['System', 'Board', 'Packaging_3D'],
	    'Engineering'    :  ['Analysis', 'Reports', 'Design Reviews']}
#-------------------------------------
# DEFINE Debug Status
#-------------------------------------
debug = True
#-------------------------------------
# Print Directory Path (Helper Func)
#-------------------------------------
def print_path(z,suffix):
	print z
	print z + suffix
#-------------------------------------
# Make a Directory Project Tree
#-------------------------------------
def make_tree_with_debug(proj,sch,root):
	counter = 0
	print "The dictionary was found to have the following: \n"
	
#-------------------------------------------------------------------------
	# Iterate over items in the dictionary, creating tuples of key/value
pairs
	
#-------------------------------------------------------------------------
	for key, values in 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 key/
values combo are: \n"
		#---------------------------------------------------------
		# Iterate over the invidividual unique values in the list
		# that is associated with each key in the dict
		#---------------------------------------------------------
		for unique in values:
			prefix = root + key +  "\\" + unique
			suffix = "\\Previous \n"
			if key == 'Schematics_PCB':
				print unique
				for item in sch:
					z = prefix + "\\" + item
					print_path(z,suffix)
			else:
				#if unique.haskeys():
				#	print unique.key
				z = prefix
				print_path(z,suffix)


make_tree_with_debug(projdir,sch_names,rootdir)



More information about the Python-list mailing list