2015-09-30 2 views
0

код до сих пор:python - Как преобразовать отношения родитель-ребенок в словарь?

for root, dirs, files in os.walk(path): 
    for directory in dirs: 
     if directory.endswith("GUI"): # Get only folders that end with GUI 
      print "Parent is: ", (os.path.join(root, directory)) 
      os.chdir(os.path.join(root, directory)) 
      for file in glob.glob("*.b"): # Get only files that end with b 
        print "Child is: ", (file) 
        dictionaryParentChild[directory] = file 
return dictionaryParentChild 

Ток: Этот код возврата только 1 родитель: 1 ребенок Желаемая: Код должен возвращать 1 родитель: многие дети

ответ

0

заменить dictionaryParentChild[directory] = file

с

if directory not in dictionaryParentChild: 
    dictionaryParentChild[directory] = [file] 
else: 
    dictionaryParentChild[directory].append(file) 

или событие лучше заменить всю внутреннюю петлю с помощью

dictionaryParentChild[directory] = [file for file in glob.glob("*.b")] 
+0

спасибо ребята за ваши ответы. он работает сейчас. – george

1
def dir_files_map(start_dir): 
    import os 
    dd = {} 
    # create dictionary where the key is folder root path 
    # and the values are the files in that folder 
    # filter files based on endswiths(string) clause 
    for root, subfolders, filenames in os.walk(start_dir): 
     for f in filenames: 
      if f.endswith('.b'): 
       dd.setdefault(root,[]).append(f) 
    return dd 
+0

Я не знал о методе 'dict.setdefault', хорошей альтернативой' collections.defaultdict'. – wap26