Boris Lai
Boris Lai

Reputation: 1

How do I read a text file and make it into a dictionary in Python?

I want to create a dictionary in Python from a text file.

The text file is given like the following:

Name,birthday,deathdate
Alan,Jan6,Dec12
Jovi,Oct6,Feb6
Kyle,June4,May9

The first line has all the keys and the next few lines are values that map onto those keys in order. The expected result is a dictionary where the name and birthday and deathdate are keys and the values map onto the birthdays.

{
    Name:[Alan,Jovi,Kyle],
    birthday:[Jan6,Oct6,June4],
    deathdate:[dec12,feb6,may9]
} 

So, how would I create a dictionary like so?

Upvotes: 0

Views: 2319

Answers (4)

Steve Misuta
Steve Misuta

Reputation: 1033

assuming the data is in the text file 'data.txt':

>>> import pandas as pd
>>> my_dict = pd.read_csv('data.txt').to_dict('list')
>>> my_dict
{'Name': ['Alan', 'Jovi', 'Kyle'],
 'deathdate': ['Dec12', 'Feb6', 'May9'],
 'birthday': ['Jan6', 'Oct6', 'June4']}

Upvotes: 0

Adam Smith
Adam Smith

Reputation: 54163

If you really want that output, then try:

import csv

with open("yourfile.txt") as f:
    reader = csv.reader(f)
    headers = next(reader)
    lines = list(reader)

result = dict(zip(headers, zip(*lines)))
# {'birthday': ('Jan6', 'Oct6', 'June4'),
#  'name': ('Alan', 'Jovi', 'Kyle'),
#  'deathdate': ('Dec12', 'Feb6', 'May9')}

zip(*some_list) is a useful idiom to convert rows to columns. Here we use it to pair header names with their columns.

Do note that this creates tuples, not lists, in the resultant dictionary. If you need lists instead, you'll have to coerce them yourself in a dictionary comprehension

result = {header: list(values) for header,values in zip(headers, zip(*lines))}
# {'birthday': ['Jan6', 'Oct6', 'June4'],
#  'name': ['Alan', 'Jovi', 'Kyle'],
#  'deathdate': ['Dec12', 'Feb6', 'May9']}

Upvotes: 2

chappers
chappers

Reputation: 2415

If you're willing to install pandas this can be done in one line:

import pandas as pd
pd.read_csv('yourfile.txt').to_dict("list")

Output:

{'Name': ['Alan', 'Jovi', 'Kyle'],
 'birthday': ['Jan6', 'Oct6', 'June4'],
 'deathdate': ['Dec12', 'Feb6', 'May9']}

Upvotes: 0

Saeid
Saeid

Reputation: 4255

Assuming you are reading from a csv file Named in.txt. First you read all the lines from file and store them in a list. Then you should create an empty dict. Then we assign a empty list to each item in first line. Then we iterate all other lines and append them to their respective lists.

L = []
with open('in.txt','r') as f:
    for line in f:
        l = line.strip().split(',')
        L.append(l)
M = {}
for key in L[0]:
    M[key] = []
for i in range(1,len(L)):
    for j in range(len(L[i])):
        M[ L[0][j] ].append(L[i][j])
print M

Output:

{'deathdate': ['Dec12', 'Feb6', 'May9'], 'birthday': ['Jan6', 'Oct6', 'June4'], 'Name': ['
Alan', 'Jovi', 'Kyle']}

Upvotes: 0

Related Questions