Search code examples
pythongitpython

get dictionary of files and directories from git repository


I'm trying to get dictionary of directories and files from git repository like this:

{"dir1": ["file1", "file2", "dir2", "dir3"], "dir2": {"file3", "dir4"}}

I know how to get list of files, the problem is how to transform it into dictionary like this.

My list of files looks like this:

["dir/dir1/file1", "dir/dir1/file2", "dir/dir1/dir2/somefile"]

Solution

  • Feel so stupid now... I used this code:

    directories = {'': set()}
    
    for f in files:
        splitted = f.split("/")
        directories[''].add(splitted[0])
    
        for i in range(len(splitted)):
            if i == len(splitted)-1:
                break
    
            d = ''
            for j in splitted[0:i+1]:
                d += j + os.path.sep
    
            d = d[0:-1]
    
            if not d in directories:
                directories[d] = set()
    
            directories[d].add(splitted[i+1])