-1

I am using Python 2; how can I migrate an array to multiple dimensions? example:

a = ['a', 'b', 'c', ...]

To:

foo['a']['b']['c']...

And check if exist, example have multiple arrays:

a = ['a', 'b', 'c']
b = ['a', 'x', 'y']

The result:

foo['a'] -> ['b'], ['x']
foo['a']['b'] -> ['c']
foo['a']['x'] -> ['y']

I need this for making a file dir tree navigation, for each path discovered need add the paths and files, the paths is get from db. Need separate a navigation by example:

http://foo.site/a ->
    /b
    /c
    /d

http://foo.site/a/b ->
    /file1.jpg
    /file2.jpg

For each path make a split by / and need make multisimensional array or dictionary with each path and files availables.

Hack-R
  • 22,422
  • 14
  • 75
  • 131
e-info128
  • 3,727
  • 10
  • 40
  • 57

2 Answers2

0

It's not really clear what you are asking,

Nevertheless, you can define a simple tree structure like this:

import collections

def tree():
    return collections.defaultdict(tree)

And use it as follow:

foo = tree()
foo['a']['b']['c'] = "x"
foo['a']['b']['d'] = "y"

You get:

defaultdict(<function tree at 0x7f9e4829f488>,
            {'a': defaultdict(<function tree at 0x7f9e4829f488>,
                              {'b': defaultdict(<function tree at 0x7f9e4829f488>,
                                                {'c': 'x',
                                                 'd': 'y'})})})

Which is similar to:

{'a': {'b': {'c': 'x', 'd': 'y'})})})

EDIT

But you also ask for β€œFor each path make a split by / and need make multidimensional array or dictionary with each path and files available.”

I usually use os.walk to search files in directories:

import os
import os.path


start_dir = ".."

result = {}
for root, filenames, dirnames in os.walk(start_dir):
    relpath = os.path.relpath(root, start_dir)
    result[relpath] = filenames
Laurent LAPORTE
  • 21,958
  • 6
  • 58
  • 103
0

This solution works for me using eval and Dictionaries of dictionaries merge :

def __init__(self):
    self.obj = {}

def setPathToObject(self, path):
    path_parts = path.replace('://', ':\\\\').split('/')
    obj_parts  = eval('{ \'' + ('\' : { \''.join(path_parts)) + '\' ' + ('}' * len(path_parts)))
    obj_fixed  = str(obj_parts).replace('set([\'', '[\'').replace('])}', ']}').replace(':\\\\', '://')
    obj        = eval(obj_fixed)
    self.obj = self.recMerge(self.obj.copy(), obj.copy())
    return obj

def recMerge(self, d1, d2):
    for k, v in d1.items():
        if k in d2:
            if all(isinstance(e, MutableMapping) for e in (v, d2[k])):
                d2[k] = self.recMerge(v, d2[k])
            elif all(isinstance(item, list) for item in (value, dict2[key])):
                d2[key] = v + d2[k]
    d3 = d1.copy()
    d3.update(d2)
    return d3

Testing:

setPathToObject('http://www.google.com/abc/def/ghi/file1.jpg')
setPathToObject('http://www.google.com/abc/xyz/file2.jpg')
setPathToObject('http://www.google.com/abc/def/123/file3.jpg')
setPathToObject('http://www.google.com/abc/def/123/file4.jpg')
print self.obj

> { 'http://www.google.com': { 'abc': { 'def': { 'ghi': [ 'file1.jpg' ], '123': [ 'file3.jpg', 'file4.jpg' ] }, 'xyz': [ 'file2.jpg' ] } } }

Works on Python 2.

e-info128
  • 3,727
  • 10
  • 40
  • 57