Helloimjs0n
Helloimjs0n

Reputation: 67

Text File to Dictionary with multiple columns

I have a text file with the following content in it

last name, first name, email, some arbitrary id number, and a phone number.

Hill, Jonah, [email protected], 015666, 123-456-7890

Reynolds, Ryan, [email protected], 1081254, 789-456-1230

Baccarin,Morena, [email protected], 1011340, 159-753-4561

...

I want to make a dictionary for each row, but have keys to name such as last name, firstname etc.

here's the code I'm trying

d = {}

with open("oldFile.txt") as f:

d = dict(x.rstrip().split(None, 1) for x in f)

print d 

I get something like this with all the content in the file in one whole dictionary

{'"hil"': '"jonah" "jonahhill@outlook" "015666" "123-456-7890"'...}

The results I'm looking for is

First person:

{lastname: "hill" , firstname: "Jonah", email: "[email protected]...}

Second person:

{Reynolds, Ryan, [email protected], 1081254, 789-456-1230}

Third person: ...

I want keys to print them out individual such as

in file1 print out first person and I get

First person:

{lastname: "hill" , firstname: "Jonah", email: "[email protected]...}

Upvotes: 0

Views: 4781

Answers (2)

Areeb
Areeb

Reputation: 406

Something like this should get the job done:

keys = ['lastname', 'firstname', 'email', 'id', 'phone']
file = open('oldFile.txt', 'r')
results = []
while True:
    line = file.readline()
    if not line:
        break
    else:
        content = line.split(', ')
        dict = {}
        index = 0
        for value in content:
            if value != '\n':
                pair = {keys[index]: value}
                dict.update(pair)
                index += 1
        if dict != {}:                          # Prevent empty lines from appending to results
            results.append(dict)

for dict in results:
    print dict

Upvotes: 1

Rikka
Rikka

Reputation: 1049

You need zip.

keys = ['lastname', 'firstname', 'email', 'id', 'phone']
dicts = []
with open("oldFile.txt") as f:
    for line in f:
        # Split each line.
        line = line.strip().split()
        # Create dict for each row.
        d = dict(zip(keys, line))
        # Print the row dict
        print d
        # Store for future use
        dicts.append(d)

The dictionaries for each row are available in the list dicts.

Upvotes: 1

Related Questions