从文件和os.listdir构建字典Python
我正在使用os.listdir和一个文件来创建一个字典。我分别从它们那里获取键和值。
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
谢谢你的阅读!
1 个回答
2
你需要同时遍历文件名和输入文件的每一行。把你原来的嵌套循环换成下面这个:
for name, line in zip(event_list, coords_file.readlines()):
adict.setdefault(name, []).append(line.strip())
在这里,我把你的循环内容简化成了一行。
如果要处理的数据量非常大,可以把 zip
换成它的懒惰版本 izip
:
from itertools import izip
for name, line in izip(event_list, coords_file):
# as before
顺便说一下,在一个函数中间使用 chdir
只是为了获取一个文件,这样的做法不太好。你可以直接用 open(os.path.join(path, 'reloc_coord_complete'))
来打开正确的文件。