### 从[parentid，name]目录dict到完整路径dict

``````D = {0: [-1, 'C:'],
1: [0, 'BLAH'],
2: [0, 'TEMP'],
3: [1, 'BOOO'],
4: [1, 'AZAZ'],
5: [2, 'ABCD']}
``````

``````FULLPATHS = {}
for key, path in D.iteritems():
newpath = path[1]
if path[0] != -1:
newpath = FULLPATHS[path[0]] + '\\' + newpath
FULLPATHS[key] = newpath
``````

`````` {0: 'C:', 1: 'C:\\BLAH', 2: 'C:\\TEMP', 3: 'C:\\BLAH\\BOOO', 4: 'C:\\BLAH\\AZAZ', 5: 'C:\\TEMP\\ABCD'}
``````

`````` D = {0: [-1, 'C:'],
7: [0, 'TEMP'],
3: [122, 'BOOO'],
4: [122, 'AZAZ'],
5: [7, 'ABCD'],
122: [0, 'BLAH']}
``````

#### 2 个答案:

``````FULLPATHS=dict()
for k in D:
parent = D[k][0]
chain = [ D[k][1] ]
while parent != -1: # here I assume root's parent is always -1
chain.append(D[parent][1])
parent = D[parent][0]
FULLPATHS[k] = '\\'.join(reversed(chain))
``````

``````FULLPATHS = { 0: 'C:' }
for k in D:
i = k
chain = []
while i not in FULLPATHS:
chain.append(D[i][1])
i = D[i][0]
FULLPATHS[k] = '\\'.join([FULLPATHS[i]] + list(reversed(chain)))

print(FULLPATHS)
``````

``````FULLPATHS = {0: 'C:'}

def do(id):
parentid = D[id][0]
name = D[id][1]
if id not in FULLPATHS:
if parentid not in FULLPATHS:
do(parentid)
FULLPATHS[id] = FULLPATHS[parentid] + '\\' + name

for k, v in D.iteritems():
do(k)

print FULLPATHS

#{0: 'C:', 3: 'C:\\BLAH\\BOOO', 4: 'C:\\BLAH\\AZAZ', 5: 'C:\\TEMP\\ABCD', 7: 'C:\\TEMP', 122: 'C:\\BLAH'}
``````