Home > Net >  How to sort a dictionary that is already sorted in descending order, so that the people with similar
How to sort a dictionary that is already sorted in descending order, so that the people with similar

Time:05-17

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?

CodePudding user response:

I would sugest to Sort by reverse average for descending order (so -1 * n), and then by name for alphabetic ordering. For example:

names_strng = """
Ayda,19
Alex,18
Jack,17
George,17
Robbie,15
"""


my_dct = dict(s.split(',') for s in names_strng.strip().split('\n'))

print(my_dct)

my_dct_srted = dict(sorted(my_dct.items(), key=lambda pare: (-int(pare[1]), pare[0])))

print(my_dct_srted)

Out:

{'Ayda': '19', 'Alex': '18', 'Jack': '17', 'George': '17', 'Robbie': '15'}
{'Ayda': '19', 'Alex': '18', 'George': '17', 'Jack': '17', 'Robbie': '15'}
  • Related