Reputation: 443
I'm taking a CSC 110 project. I am trying use dictionaries for our assignment even though we haven't learned them yet.
I have a file of countries and how many medals they won separated by new line characters. EX:
Afghanistan
0
0
0
Albania
0
0
0
Algeria
0
2
0
Each line after the country is the medals they earned starting with gold and working its way down to bronze.
I want to take these and store them in a dictionary with the structure looking something like this. dict={Afghanistan: [0,0,0], Albania: [0,0,0]}
What I have :
olympic_stats = {}
fileIn = open('test.txt', 'r')
line = fileIn.readline()#Initialize Loop
counter = 0
while line != '':
if counter == 4:
counter = 0
if counter%4 == 0:#First Pass, COUNTRY
country_name = line.rstrip()
elif counter%4 == 1:#Second Pass, GOLD
gold_medals = int(line)
elif counter%4 == 2:#Third Pass, SILVER
silver_medals = int(line)
else: #Fourth Pass, BRONZE
bronze_medals = int(line)
#update Counter
counter += 1
if counter == 4:
olympic_stats[country_name] = [gold_medals, silver_medals, bronze_medals]
line = fileIn.readline()#Update Loop
While this works it is nasty and over complicated. I'm trying to come up with a new way to do this.
Upvotes: 1
Views: 77
Reputation: 128
While your answer isn't super concise its not 'bad' per say. I might do something like this:
olympic_stats = {}
while line:
line_str = line.rstrip()
if line_str[0].isalpha():
country = line_str
olympic_stats[country] = []
else:
olympic_stats[country].append(line_str)
Upvotes: 1
Reputation: 24711
Your loop here is pretty clumsy - you can do better. You could, for example,
file.readlines()
)which I have done here:
olympic_stats = {}
fileIn = open('test.txt', 'r')
fileLines = fileIn.readlines()
counter = 0
while counter < len(fileLines):
country_name = fileLines[counter]
gold_metals = fileLines[counter + 1]
silver_metals = fileLines[counter + 2]
bronze_metals = fileLines[counter + 3]
olympic_stats[country_name] = [gold_medals, silver_medals, bronze_medals]
counter += 4
There are more concise but much more complicated methods of doing this, by involving list comprehension and numpy
or itertools
, but those are more advanced topics and this should suffice for the time being.
While implementing this you might come up against errors when the number of lines in the file isn't easily divisible by four - I'll leave you to figure out how to fix that issue on your own, as it's a valuable learning experience and not too hard.
Upvotes: 1