python - 如何将父子关系转换为字典?

时间:2015-09-30 09:42:57

标签: python dictionary

目前的代码是:

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个父母:很多孩子

2 个答案:

答案 0 :(得分:1)

function keyMap(src, target){
  target = target || {};
  Object.keys(src).forEach(function(propName){
     var prop = src[propName];
     if(typeof prop == "object"){
       target[propName] = Object.keys(prop).join(',');
       keyMap(prop, target);
     }
  });
  return target;
};

var result = keyMap({
"centers" : {
  "ER" : {
    "admin":{
      "users" : {
        "emp1" : {
          "password" : "abcdefgh",
          "username" : "pankaj-roy"
        },
        "emp2" : {
          "password" : "12345678",
          "username" : "niketan-shah"
        }
      }
    }
  }
}
});
                      
console.log(result);

答案 1 :(得分:0)

替换dictionaryParentChild[directory] = file

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

或事件更好地用

替换整个内部for循环
dictionaryParentChild[directory] = [file for file in glob.glob("*.b")]