Search code examples
pythonfiledictionaryfile-read

Python: Read a file and turn it into a dictionary with first+second line being the key


I'm trying to read a file that look something like this:

Lee
Louise
12345678
711-2880 Nulla St. Mississippi
Chapman
Eric
27681673
Ap 867-859 Sit Rd. New york
(...)

and make it into a dictionary with the last and firstname as keys and with the values being lastname, firstname, tel and address. It should look someting like this:

{'Lee Louise': ['Lee','Louise','12345678','711-2880 Nulla St. Mississippi'],'Chapman Eric': ['Chapman','Eric','27681673','Ap #867-859 Sit Rd. New york']}

And this is what I've done so far:

d = dict()
fr = open('file.txt', 'r').readlines()
info = [k.split('\n') for k in fr]
for k in range(len(info)):
    if k % 4 == 0:
        list = info[k :k + 4]
        new_list = [b[0] for b in list]
        d[info[k][0]] = new_list
return d

I only managed to make the lastnames into keys.. What can I do to make both last and firstname into keys?


Solution

  • There are several issues with your code

    • You are overriding Python function list- bad idea.
    • You are already reading lines - use strip('\n'), split creates parasitic list.
    • Use range with step 4
    • Did I mention 1-letter variable names?

    I would re-write fragment of your code as

    info = open(...).read().splitlines()  # Saves from re-building list
    for offset in range(0, len(info), 4):
        d[' '.join(info[offset: offset + 2]) = info[offset: offset + 4]
    

    No parasitic list - saving from new_list mess