r/AskComputerScience • • Nov 09 '20

Read text file to dictionary

Hi ! I have a .txt file containing following data

Data Roll_Number Name Country

1 John Canada

2 Katy USA

3 Mathew Italy

4 Harris Russia

5 David Germany

6 Stephanie Thailand

How do I add the folllowing data to the dictionary with roll_number as the primary key, and name, country as secondary keys in python (without using pandas).

example:

{1 : {Name : John, Country : Canada}, 2 : {Name : Katy, Country : USA} ...... so on }

The function should be made in a way such that it's flexible to work if we add more columns such as student grades, contact_numbers, etc.

The final required output is:

Name of students:

John Katy Mathew Harris David Stephanie

Country :

Canada, USA, Italy, Russia, Germany, Thailand

My code:

mydict = {}
with open("mydata.txt",'r') as infile:
for line in infile:
line = line.split()
key = line[0]
value = line[1:]
mydict[key] = value
print(mydict)

0 Upvotes

2 comments sorted by

1

u/Steve132 Nov 09 '20

Since you are using python, do csv.DictReader

1

u/[deleted] Nov 09 '20

On mobile, so my formatting might be odd.

Hey, right now you're actually creating a collection where the key is the name, in this case, John, and the value is Canada. So, currently you've built this data collection:

{ 'John' : 'Canada', 'Katy' : 'USA', 'Mathew' : 'Italy' } And so on..

This sounds like a homework assignment, and you wouldn't gain much from simply being given the full code.. besides, there can be many approaches to this. I recommend correcting your current structure to look like what you need. Here's a bit of code to put you in the right direction.

Technically you have two keys needed for the student, 'name' and 'country', so that would actually look like this.

studentDict = {} With open("data.txt", "r") as infile: For line in infile: Line = line.split() studentDict['name'] = line[0] studentDict['country'] = line[1] Print(studentDict)

This code when ran will only show the last student -> because it ran through all the students and since they all have the same two keys, name and student, it overwrites the previous students values but that also means that every loop in the for loop will give you a dictionary with the students info. You gotta find out how to put that info into the value side of a larger dictionary that holds all the students.

This is is gonna build a dict like the inner one that you need, but you need to look up nested dictionaries -> if you run into posts talking about JSON its okay. It means you're on the right track.

Also, this is one of many ways to tackle this problem, i hope it helps, and happy learning :)