用值替换键并写入新文件Python

时间:2011-11-08 07:14:23

标签: python dictionary

我在尝试使用相应的值替换文件中的密钥(字典)时遇到了问题。更多细节:名为event_from_picks的输入文件如下所示:

EVENT2593
EVENT2594
EVENT2595

EVENT41025
EVENT2646
EVENT2649

另外,我的词典由reloc_event_coords_dic()创建,如下所示:

{'EVENT23595': ['36.9828   -34.0538   138.1554'], 'EVENT2594': ['41.2669   -33.0179   139.2269'], 'EVENT2595': ['4.7500   -32.7926   138.1523'], 'EVENT41025': ['16.2453   -32.9552   138.2604'], 'EVENT2646': ['5.5949   -32.4923   138.1866'], 'EVENT2649': ['7.9533   -31.8304   138.6966']}

我最终想要的是一个带有值而不是键的新文件。在这种情况下,一个名为receiver.in的新文件将如下所示:

36.9828   -34.0538   138.1554
41.2669   -33.0179   139.2269
4.7500   -32.7926   138.1523
16.2453   -32.9552   138.2604
5.5949   -32.4923   138.1866
7.9533   -31.8304   138.6966

我的错误功能(我知道我必须遇到循环问题,但我无法弄清楚是什么)到目前为止:

def converted_lines ():
    file_out = open ('receiver.in', 'w')
    converted_lines = []
    event_dict = reloc_event_coords_dic()
    data_line = event_dict.items() # Takes data as('EVENT31933', ['10.1230 -32.8294 138.1718'])
    for element in data_line:
        for item in element:
            event_number = element[0] # Gets event number
            coord_line = event_dict.get (event_number, None)   
    with open ('event_from_picks', 'r') as file_in:
        for line in file_in:
            if line.startswith("  "):
                continue
            if event_number:
                converted_lines.append ("%s" % coord_line)
        file_out.writelines(converted_lines)

感谢阅读!

2 个答案:

答案 0 :(得分:0)

只需执行以下操作:

with open('receiver.in', 'w') as f:
    f.writelines([v[0] for v in reloc_event_coords_dic().itervalues()])

答案 1 :(得分:0)

您的第一个循环只留下coord_line变量中的最后一对。

更好

event_dict = reloc_event_coords_dic()
with open ('event_from_picks', 'r') as file_in:
    with open('receiver.in', 'w') as file_out:
        for in_line in file_in:
            file_out.writelines(event_dict[in_line.strip()])

(未经测试,但你应该得到逻辑)。