2011-11-06 66 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