Imagine we have a dictionary of peoples' names and averages which are sorted by value (average) in descending order. I want to sort the dictionary in a way that people with similar averages appear in alphabetic order. For example:
Ayda,19
Alex,18
Jack,17
George,17
Robbie,15
I want to get this output:
Ayda,19
Alex,18
George,17
Jack,17
Robbie,15
I want to modify the following code:
def calculate_sorted_averages(file1, file2):
with open (r'C:\Users\sony\Desktop\Python with Jadi\file1.csv', 'r') as f1:
reader=csv.reader(f1)
d={}
for row in reader:
name=row[0]
average=float(row[1])
d[name]=average
sorted_dict=dict(sorted(d.items(), key=operator.itemgetter(1), reverse=False))
with open (r'C:\Users\sony\Desktop\Python with Jadi\file2.csv', 'w', newline='') as f2:
for key in sorted_dict.keys():
writer=csv.writer(f2)
writer.writerow([key,sorted_dict[key]])
I think sorting a part of a dictionary will be helpful but I don't know how to split a dictionary, sort it alphabetically, and then merge it back together. Can you please help to figure it out?