I've got a problem trying to replace keys (dictionary) that I have in a file, with its corresponding values. More details: an input file called event_from_picks looks like:

EVENT2593
EVENT2594
EVENT2595

EVENT41025
EVENT2646
EVENT2649

Also, my dictionary, created by reloc_event_coords_dic() looks like:

{'EVENT23595': , 'EVENT2594': , 'EVENT2595': , 'EVENT41025': , 'EVENT2646': , 'EVENT2649': }

What I'd like to end up with, is a new file with the values instead of the keys. In this case, a new file called receiver.in which will look like:

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

My wrong function (I know I must have a problem with loops but I can't figure out what) so far is:

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)

Thanks for reading!

I think you want something like this, but post back if I do not understand

## store the recs in a set to make look up fast
## this assumes no two records are the same
recs_list = open('event_from_picks', 'r').readlines()
event_set = set(recs_list)

for key, list_of_numbers in event_dict.items():
    if key in event_set:
        ## event_set.remove(key)   ??? only use first rec found
        for item in list_of_numbers:
            output_file.write("%s " % (item))
        output_file.write("\n")
output_file.close()

I tried with this

def converted_lines ():
    recs_list = open('event_from_picks', 'r').readlines()
    event_set = set(recs_list)
    event_dict = reloc_event_coords_dic()
    file_out = open ('receiver.in', 'w')
    for key, list_of_numbers in event_dict.items():
        if key in event_set:
            #event_set.remove(key)
            for item in list_of_numbers:
                output_file.write("%s " % (item))
                output_file.write("\n")
                output_file.close()

but it doesn't write anything on the file and actually with 'print' item or key it gives nothing...

Print event_dict to see if it contains anything. Also, output_file should be file_out, and the close() statement is indented incorrectly.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.