Reputation: 1
I have a dictionary named dict
that stores names and float averages, and I want to store the sorted averages with names in a file, but when I use a loop to find the key (students' names) it prints duplicated name.
print(dict)
sorted_list = sorted(dict.values() , key = float)
sorted_dict = list()
for i in sorted_list:
for j in dict:
if dict[j] == i:
sorted_dict.append([j,dict[j]])
break
print(sorted_dict)
Take a look at the output:
OrderedDict([('mandana', '5'), ('hamid', '6.066666666666666'), ('sina', '11.285714285714286'), ('sara', '9.75'), ('soheila', '7.833333333333333'), ('ali', '5'), ('sarvin', '11.375')])
[['mandana', '5'], ['mandana', '5'], ['hamid', '6.066666666666666'], ['soheila', '7.833333333333333'], ['sara', '9.75'], ['sina', '11.285714285714286'], ['sarvin', '11.375']]
Upvotes: 0
Views: 67
Reputation: 23192
Your algorithm looks up the name corresponding to a given number. This leads to wrong results if the same number occurs for more than one name. Here, for 5
, which actually belongs to 'ali'
, it finds 'mandana'
first and includes it instead.
You can directly sort the name, value pairs by passing dict.items
instead of dict.values
to sorted
. The key
function would then have to take the second item of each pair and convert it to a float.
sorted_dict = sorted(dict.items(), key=lambda pair: float(pair[1]))
Upvotes: 2