title: Python - get the path of a given item from a dictionary
body: <p>I have a function that converts a file path into a dictionary:</p>
  <pre><code>def get_directory_structure(rootdir):
      &quot;&quot;&quot;
      Creates a nested dictionary that represents the folder structure of rootdir
      &quot;&quot;&quot;
      dir = {}
      rootdir = rootdir.rstrip(os.sep)
      start = rootdir.rfind(os.sep) + 1
      for path, dirs, files in os.walk(rootdir):
          folders = path[start:].split(os.sep)
          subdir = dict.fromkeys(files)
          parent = reduce(dict.get, folders[:-1], dir)
          parent[folders[-1]] = subdir
      return dir
  </code></pre>
  <p>Example output for <a href="https://i.stack.imgur.com/zlKnn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zlKnn.png" alt="this" /></a>:</p>
  <pre><code>path_dict = {'Desktop': {
                 'sensup.sh': None, 
                 'sensdown.sh': None, 
                 '1': {
                    '2': {
                       '3': {
                          '4': {}}}}}}
  </code></pre>
  <p>I need to create a function that when given the name of a file or folder from this directory, it outputs its path. For example <code>get_directory('3', path_dict)</code> would output <code>Desktop/1/2/3</code>.</p>
  <p>Here's what I tried:</p>
  <pre><code>def get_path_from_dict(base_path, base_name, ob, path=''):
          if ob and base_name in list(ob.keys()):
              path = f&quot;{base_path}{path}/{base_name}&quot;
              print(path)
              return path
          elif not ob:
              pass
          else:
              for key, value in sorted(ob.items()):
                  get_path_from_dict(base_path, base_name, value, f'{path}/{key}')
  </code></pre>
  <p>Where <code>base_path</code> is the beginning of the full path, so <code>home/user</code> in this case, <code>base_name</code> is the file name to be searched for, and <code>ob</code> is the path dictionary. When I print the final path, it comes out correctly, but when I print the return value it comes out as <code>None</code> and I'm not sure why.</p>
  <p>Output of <code>print(get_path_from_dict('/home/user', &quot;3&quot;, path_dict))</code>:</p>
  <pre><code>/home/user/Desktop/1/2/3 ((from print))
  None                     ((from return value))
  </code></pre>