sorting a list by values of a dictionary python

Viewed 81

i have a list which have element as a student registration number and i have two dictionaries with the same student registration number and thier values are the student avg grades and the student surname and name i need a sorted list which sort the student registration number in descending order by average grade and, in case of a tie, in lexicographic order by the student's surname and name, finally registration number in ascending order for example

my_dict_1 = {'1882282': 29.4, '1675598': 29.125, '1659373': 29.25, '1324812': 30.4}   # this is dict with avg grades
my_dict_2 = {'1882282': 'Iacometti Monica', '1675598': "Fiala' Ester", '1659373': "Beudo' Miriam", '1324812': 'Abucar Osman Mariarosaria'}  # this is dict_2 with student surname and name

so my return sorted list should be

sorted_list = ['1324812', '1882282', '1659373', '1675598']
2 Answers

do this :

import pandas as pd

new_dict = {'code': list(my_dict_1.keys()),
            'number': list(my_dict_1.values()),
            'name' : list(my_dict_2.values())}

df = pd.DataFrame(data=new_dict)

now we have a dataframe that has three columns : code , number and namber of them.

so it's time to sort it :

sorted_array = df.sort_values(['number', 'name', 'code'], ascending=False)

now convert anycolumn you want to the list:

sorted_list =  list(sorted_array['code']))

here you are:

['1324812', '1882282', '1659373', '1675598']

this is just a try whe nu can sort by average then merge both dict so in case of a tie it will be ordered by the student's surname ascending :

my_dict_1 = {'1882282': 29.4, '1675598': 29.125, '1659373': 29.25, '1324812': 30.4}   # this is dict with avg grades
my_dict_2 = {'1882282': 'Iacometti Monica', '1675598': "Fiala' Ester", '1659373': "Beudo' Miriam", '1324812': 'Abucar Osman Mariarosaria'}
my_dict_1 = dict(sorted(my_dict_1.items(), key=lambda kv: kv[1]))
def defaultdict(default_type):
    class DefaultDict(dict):
        def __getitem__(self, key):
            if key not in self:
                dict.__setitem__(self, key, default_type())
            return dict.__getitem__(self, key)
    return DefaultDict()
dd  = defaultdict(list)

for d in (my_dict_1, my_dict_2): # you can list as many input dicts as you want here
    for key, value in d.items():
        dd[key].append(value)
print(dict(dd))
Related