【问题标题】:Build dictionary from file and os.listdir python从文件和 os.listdir python 构建字典
【发布时间】:2011-11-06 23:28:40
【问题描述】:

我正在使用 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

感谢阅读!

【问题讨论】:

    标签: python file dictionary for-loop


    【解决方案1】:

    您需要同时遍历文件名和输入文件的行。用

    替换你的嵌套循环
    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')) 轻松打开正确的文件。

    【讨论】:

    • 那行得通,我很烂,因为我花了两天时间!我认为我的 for 循环有问题.....非常感谢!
    • @eikonal:不客气。不要忘记接受这个答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-29
    • 1970-01-01
    • 2011-12-09
    • 2012-03-08
    • 1970-01-01
    相关资源
    最近更新 更多