I'm not sure what to title this so suggestions to the title are also welcome. I'm creating a program that will read data from a file and print it in order.
The file will always contain data based on this:
- Name:1,2,3
- Name_2:4,5,6
- Name_3:10,9,8
Here's my code for getting the data from the file:
def getData(file):
data = {}
try:
with open(file + ".txt", "r") as file:
for line in file:
build = line.split(":")
data[build[0]] = build[1]
except FileNotFoundError:
with open(file + ".txt", "a") as file:
pass
return data
The returned data is :
data = {"Name": "1,2,3\n", "Name_2": "4,5,6\n", "Name_3": "10,9,8\n"
Now that I've got the data, I'm trying to "sort" it, dictionaries aren't really sortable so I used "OrderedDict." Heres the code:
def sortData(data, choice):
## Sort By Average
if choice == "Average":
for name, score in data.items():
amount = 0
for i in re.finditer("[0-9]{1,2}", score):
amount += 1
average = eval(re.sub(",","+",score))/amount
data[name] = str(average) + "\n"
od_data = collections.OrderedDict(sorted(data.items(), key=lambda t:float(t[1]), reverse=True))
for name, score in od_data.items():
sys.stdout.write("%s: %s" % (name, score))
## Sort By Highest - Lowest
elif choice == "Highest - Lowest":
od_data = collections.OrderedDict(sorted(data.items(), key=lambda t:t[1], reverse=True))
for name, score in od_data.items:
sys.stdout.write("%s: %s" % (name, score)
When the choice is "Average", the data is printed as it is supposed to and within order. When the choice is "Highest - Lowest", the data is partially printed out in order:
- Name_2:4,5,6
- Name:1,2,3
- Name_3:10,9,8
It works as it should, only if the first "number" is not "10", for some reason it seems to register in the program as "1" and "0" and therefore ends up being as the lowest entry.