2011-11-06 107 views
1

我使用os.listdir和一個文件來創建字典。我分別從中獲取鍵和值。從文件和os.listdir構建字典python

os.listdir給我:

EVENT3180 
EVENT2894 
EVENT2996 

,並從文件獲得:

3.1253 -32.8828 138.2464 
11.2087 -33.2371 138.3230 
15.8663 -33.1403 138.3051 

主要的問題是,我最終的詞典有不同的密鑰,但始終是不一樣的價值我想要的是。我試圖得到的是:

{'EVENT3180': 3.1253 -32.8828 138.2464, 'EVENT2894': 11.2087 -33.2371 138.3230, 'EVENT2996': 15.8663 -33.1403 138.3051} 

所以我認爲我的代碼循環的鍵但不超過值。總之,到目前爲止我的代碼:

def reloc_event_coords_dic(): 
    event_list = os.listdir('/Users/working_directory/observed_arrivals_loc3d') 
    adict = {} 
    os.chdir(path) # declared somewhere else 
    with open ('reloc_coord_complete', 'r') as coords_file: 
     for line in coords_file: 
      line = line.strip() #Gives me the values 
      for name in event_list: # name is the key 
       entry = adict.get (name, []) 
       entry.append (line) 
       adict [name] = entry 
      return adict 

感謝您的閱讀!

回答

2

您需要同時循環輸入文件的文件名和行。用

替換你的嵌套循環
for name, line in zip(event_list, coords_file.readlines()): 
    adict.setdefault(name, []).append(line.strip()) 

其中我冒昧地將你的循環體壓縮成一行。

如果要處理的數據量非常大,然後用它的懶惰表弟izip更換zip

from itertools import izip 

for name, line in izip(event_list, coords_file): 
    # as before 

順便說一下,在一個函數中做了chdir只是爲了搶單的文件是一種代碼味道。您可以使用open(os.path.join(path, 'reloc_coord_complete'))輕鬆打開正確的文件。

+0

這工作,我吸了,因爲我花了兩天在這!我想我對循環有問題.....非常感謝! – eikonal

+0

@eikonal:不客氣。不要忘記接受這個答案。 –

+0

沒錯;)再次感謝 – eikonal