2013-08-26 171 views
1

我有一本字典,看起來與此類似:蟒蛇連接鍵和值從字典

mydic = {'key1':['va1','va2'], 'key2':['vb1','vb2']} 

我想打印文件路徑這些,例如

/path/to/dir/key1/dir2/va1 
/path/to/dir/key1/dir2/va2 
/path/to/dir/key2/dir2/vb1 
/path/to/dir/key3/dir2/vb2 

我都試過了,

for k, v in mydic.iteritems(): 
    print "/path/to/dir/k/dir2/v" 

但是這樣一來打印出v爲列表。我如何實現上述目標?謝謝...

回答

2

您可以使用os.path.join(),像這樣:

import os 

mydic = {'key1':['va1','va2'], 'key2':['vb1','vb2']} 


BASE_DIR = os.path.join('path', 'to', 'dir') 
ADD_DIR = 'dir2' 
for k, v in mydic.iteritems(): 
    for item in v: 
     print os.path.join(BASE_DIR, k, ADD_DIR, item) 

打印:

/path/to/dir/key2/dir2/vb1 
/path/to/dir/key2/dir2/vb2 
/path/to/dir/key1/dir2/va1 
/path/to/dir/key1/dir2/va2 
+0

完美。謝謝... – iamauser

+2

這混合了窗口中的前後斜線。也許使用'BASE_DIR = os.path.join('path','to','dir')'? – Stuart

+0

@Stuart很好的接收,謝謝! – alecxe