Q:

Convert list of paths to dictionary in python

I'm making a program in Python where I need to interact with "hypothetical" paths, (aka paths that don't and won't exist on the actual filesystem) and I need to be able to listdir them like normal (path['directory'] would return every item inside the directory like os.listdir()). 
The solution I came up with was to convert a list of string paths to a dictionary of dictionaries.  I came up with this recursive function (it's inside a class):
    def DoMagic(self,paths):
        structure = {}
        if not type(paths) == list:
            raise ValueError('Expected list Value, not '+str(type(paths)))
        for i in paths:
            print(i)
            if i[0] == '/': #Sanity check
                print('trailing?',i) #Inform user that there *might* be an issue with the input. 
                i[0] = ''
            i = i.split('/') #Split it, so that we can test against different parts. 
            if len(i[1:]) > 1: #Hang-a-bout, there's more content! 
                structure = {**structure, **self. DoMagic(['/'.join(i[1:])])}
            else:
                structure[i[1]] = i[1]

But when I go to run it with ['foo/e.txt','foo/bar/a.txt','foo/bar/b.cfg','foo/bar/c/d.txt'] as input, I get:
{'e.txt': 'e.txt', 'a.txt': 'a.txt', 'b.cfg': 'b.cfg', 'd.txt': 'd.txt'}

I want to be able to just path['foo']['bar'] to get everything in the foo/bar/ directory. 
Edit:
A more desirable output would be:
    {'foo':{'e.txt':'e.txt','bar':{'a.txt':'a.txt','c':{'d.txt':'d.txt'}}}}

A:

How about this.  It gets your desired output, however a tree structure may be cleaner. 
from collections import defaultdict
import json

def nested_dict():
   """
   Creates a default dictionary where each value is an other default dictionary. 
   """
   return defaultdict(nested_dict)

def default_to_regular(d):
    """
    Converts defaultdicts of defaultdicts to dict of dicts. 
    """
    if isinstance(d, defaultdict):
        d = {k: default_to_regular(v) for k, v in d.items()}
    return d

def get_path_dict(paths):
    new_path_dict = nested_dict()
    for path in paths:
        parts = path.split('/')
        if parts:
            marcher = new_path_dict
            for key in parts[:-1]:
               marcher = marcher[key]
            marcher[parts[-1]] = parts[-1]
    return default_to_regular(new_path_dict)

l1 = ['foo/e.txt','foo/bar/a.txt','foo/bar/b.cfg','foo/bar/c/d.txt', 'test.txt']
result = get_path_dict(l1)
print(json.dumps(result, indent=2))

Output:
{
  "foo": {
    "e.txt": "e.txt",
    "bar": {
      "a.txt": "a.txt",
      "b.cfg": "b.cfg",
      "c": {
        "d.txt": "d.txt"
      }
    }
  },
  "test.txt": "test.txt"
}

