Kieee
Kieee

Reputation: 136

Create file-tree from nested dict | Python 2.7

I have a nested dictionary like this:

Main = {
    'root' : {
        'object': 'data'
        'users': {
            'otherobj': 'data'
        }
    }
}

Upvotes: 2

Views: 1336

Answers (2)

hoyland
hoyland

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
  • and so on

So let's break this down a bit. You basically need the ability to do two things:

  • determine whether the value of a key in your dictionary is "data" or another dictionary
  • given some data, write it out to a file with a given path

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

adgon92
adgon92

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

Related Questions