Python - How To Update A Multi-dimensional Dict
Follow up of my previous question: Python - How to recursively add a folder's content in a dict. When I build the information dict for each file and folder, I need to merge it to t
Solution 1:
Of course you can create nested dictionaries on-the-fly. What about this:
# Example path, I guess something like thisis produced by path2indice?!
indices = ("home", "username", "Desktop")
tree = {}
d = tree
for indice in indices[:-1]:
if indice not in d:
d[indice] = {}
d = d[indice]
d[indices[-1]] = "some value"
print tree # this will print {'home': {'username': {'Desktop': 'some value'}}}
Solution 2:
I'm not entirely sure I understand what you're asking for, but it seems like a textbook case for recursion. I think something like this might be of use (as a replacement for your current method):
import os
FILES = ...
def process(directory):
dir_dict = {}
for file inos.listdir(directory):
filename = os.path.join(directory, file)
ifos.path.isdir(file):
dir_dict[file] = process(filename)
else: # assuming it needs to be processed as a file
dir_dict[file] = Analyse(filename)
return dir_dict
(based on phihag's answer to your other question) Basically this constructs a dict for each directory containing the analyzed information about the files in that directory, and inserts that dict into the dict for the parent directory.
If it's not this, I think dict.update
and/or the collections.defaultdict
class may need to be involved.
Post a Comment for "Python - How To Update A Multi-dimensional Dict"