ryan2405
ryan2405

Reputation: 63

Sorting decimals within a dictionary

I have almost finished my sorting problem, with many hours surfing the web I stumbled upon an extremely helpful guide to sorting dictionaries within Python, but a problem that seems to be reoccurring whenever I try to sort is the fact that my data that requires sorting is a float data type.

Example of how I create 'names'x'' and 'avmph'x'' variables

file1=open("1.txt",'r')
line1=file1.readlines()
names1=line1[0].rstrip('\n')
avmph1=line1[3].rstrip('\n')

mydict={names1:avmph1,
    names2:avmph2,
    names3:avmph3,
    names4:avmph4,
    names5:avmph5,
    names6:avmph6,
    names7:avmph7,
    names8:avmph8,
    names9:avmph9,
    names10:avmph10}

for key, value in sorted(mydict.items(),key=lambda item:(item[1],item[0])):
    print ("%s : %s" % (key,value))

The result I get is as follows:

1987dodd : 10
3219guy : 11.6
2198adams : 12.2
8765james : 13.2
4321jones : 6.3
5432kane : 6.3
9876smith : 6.5
8754smith : 8.7
7654max : 9
6543dunne : 9.5
#seems to sort values that are greater than 10 (2 digits before decimal) separately 

I am unsure of how to edit my exsisting code as .sort(float) worked on my 'avmph' alone, this method should allow me to return both 'names' and 'avmph'. Any help would be much obliged.

Upvotes: 3

Views: 125

Answers (1)

Padraic Cunningham
Padraic Cunningham

Reputation: 180441

You need to cast to float:

(float(item[1]),item[0]))

You are sorting the strings not the actual float value:

In [1]: "13.2" < "6.3"
Out[1]: True

In [2]: float("13.2") < float("6.3")
Out[2]: False

Because ord("6") > ord("1") "6.3" is considered > "13.2".

Not totally sure how the name and avmph line up but you if they are on every second line you can do something like:

with open("1.txt") as f:
    d = {next(f).rstrip():next(f).rstrip() for line in f}

next(f).rstrip() advances to the next line each call so we ass every second line as key and value. with will automatically close your file.

Upvotes: 6

Related Questions