eikonal
eikonal

Reputation: 171

Build dictionary from file and os.listdir python

I'm using os.listdir and a file to create a dictionary. I'm getting keys and values from them respectively.

os.listdir gives me:

EVENT3180
EVENT2894
EVENT2996

and from the file I get:

3.1253   -32.8828   138.2464
11.2087   -33.2371   138.3230
15.8663   -33.1403   138.3051

The main problem is that my final dictionary has different keys but always the same value which is not what I want. What I'm trying to get is:

{'EVENT3180': 3.1253   -32.8828   138.2464, 'EVENT2894': 11.2087   -33.2371   138.3230, 'EVENT2996': 15.8663   -33.1403   138.3051}

So I think my code is looping over the keys but not over the values. Anyway, my code so far:

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

Thanks for reading!

Upvotes: 1

Views: 1386

Answers (1)

Fred Foo
Fred Foo

Reputation: 363817

You'll want to loop over the filenames and the lines of the input file simultaneously. Replace your nested loops with

for name, line in zip(event_list, coords_file.readlines()):
    adict.setdefault(name, []).append(line.strip())

where I took the liberty of compressing your loop body into one line.

If the amount of data to be processed is extremely large, then replace zip with its lazy cousin izip:

from itertools import izip

for name, line in izip(event_list, coords_file):
    # as before

Btw., doing a chdir in the middle of a function just to grab a single file is a code smell. You can easily open the right file with open(os.path.join(path, 'reloc_coord_complete')).

Upvotes: 2

Related Questions