Reputation: 136
I have a nested dictionary like this:
Main = {
'root' : {
'object': 'data'
'users': {
'otherobj': 'data'
}
}
}
/tree/
where the name of each dict is the name of the folderUpvotes: 2
Views: 1336
Reputation: 1824
If I'm understanding properly, you want to end up with something like the following:
root/object
containing data
root/users/otherobj
containing data
So let's break this down a bit. You basically need the ability to do two things:
I'm going to leave it to you to write these functions, but I'll assume they have the following signatures:
def is_data(obj)
returning True/False
(this could be not isinstanceof(obj, dict)
unless your data objects could be dicts with some special properties)def write_data(directory, filename, obj)
At this point, we're ready to write a function to walk the tree. I'm going to assume you pull the first key and dictionary out of Main
. For each (key, value) pair, we need to check if the value is "data" or if it's another dict. If it's data, write it out. If it's another dict, we add the key to our path and call our function on that dict.
def walk(root_directory, obj_dict):
for k, v in obj_dict.iteritems():
if is_data(v):
# write the file
write_data(root_directory, k, v)
else: # it's another dict, so recurse
# add the key to the path
new_root = os.path.join(root_directory, k) # you'll need to import os
walk(new_root, v)
Upvotes: 0
Reputation: 219
This code snippet should help. Here I assume that the python script will be run in target local directory.
import os
# dir_definition = <your 'Main'>
def create_dirs(dir_definition):
for dir_dame, sub_dir in dir_definition.items():
os.mkdir(dir_dame)
if isinstance(sub_dir, dict):
create_dirs(sub_dir)
Upvotes: 1