从file和os.listdir python构建字典

时间:2011-11-06 23:28:41

标签: python file dictionary for-loop

我正在使用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 个答案:

答案 0 :(得分: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'))轻松打开正确的文件。