Home > Mobile >  Convert a text file into a large dictionary Python
Convert a text file into a large dictionary Python

Time:11-29

I have a text file that looks like this:

subjects ENGLISH, MATHS, SCIENCE

Joe, A, A, B

Dave, A, B, C

Will, D, D, E

And I want to put it into a dictionary using Python

{’Joe’:{’ENGLISH’:A,’MATHS’:A,’SCIENCE’:B},
’Dave’:{’ENGLISH’:A,’MATHS’:B,’SCIENCE’:C},
’Will’:{’ENGLISH’:D,’MATHS’:D,’SCIENCE’:E}}

How would I go about doing this in one dictionary?

CodePudding user response:

Assuming you have a file called file.txt with the following contents:

subjects ENGLISH, MATHS, SCIENCE

Joe, A, A, B

Dave, A, B, C

Will, D, D, E

Try using * unpacking:

results = {}
with open('file.txt') as file:
    _, *subjects = next(file).split(' ')  # Read header row
    subjects = [s[:-1] for s in subjects]  # Remove trailing comma/newline from subjects
    for line in file:
        if line != '\n':  # Skip empty lines
            name, *grades = line.strip().split(', ')
            results[name] = dict(zip(subjects, grades))
print(results)

You can also define the subjects in code and skip the header row completely:

subjects = ['ENGLISH', 'MATHS', 'SCIENCE']
results = {}
with open('file.txt') as file:
    next(file)  # Skip header row since we have defined subjects in code...
    for line in file:
        if line != '\n':  # Skip empty lines
            name, *grades = line.strip().split(', ')
            results[name] = dict(zip(subjects, grades))
print(results)

Output:

{'Joe': {'ENGLISH': 'A', 'MATHS': 'A', 'SCIENCE': 'B'}, 'Dave': {'ENGLISH': 'A', 'MATHS': 'B', 'SCIENCE': 'C'}, 'Will': {'ENGLISH': 'D', 'MATHS': 'D', 'SCIENCE': 'E'}}

CodePudding user response:

We can read the file by using pd.read_csv() and convert the pd to a dictionary by using: df.to_dict('index')

CodePudding user response:

You could convert your text file to CSV

Name, ENGLISH, MATHS, SCIENCE

Joe, A, A, B

Dave, A, B, C

Will, D, D, E

Then use the pandas' library to read the CSV file and convert it into the dictionary.

>>> import pandas as pd
>>> pd.read_csv('file_path.csv',index_col='Name').transpose().to_dict()

{'Joe': {'ENGLISH': ' A', 'MATHS': ' A', 'SCIENCE': ' B'}, 'Dave': {'ENGLISH': ' A', 'MATHS': ' B', 'SCIENCE': ' C'}, 'Will': {'ENGLISH': ' D', 'MATHS': ' D', 'SCIENCE': ' E'}}

  • Related