Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a Python Dictionary by Priority

I have a python dictionary consisting of (names,value) pairs like so

pyDictionary = {"Bob":12,"Mellissa":12,"roger":13}

What i would like to do is to obtain a sorted version of the above dictionary where the sorting is done by giving first prority to the value and if the value for two pairs are the same then the comparision should be made by lexographically comparing the names.

How can i acheive this in python3.7?

like image 396
Atif Farooq Avatar asked Dec 31 '22 23:12

Atif Farooq


1 Answers

You can use sorted with a key, and build an OrderedDict from the result to mantain order.

(the last step is only necessary with python 3.6 <, in Python 3.7 dicts are ordered on their key insertion time)


from collections import OrderedDict
d = {"Mellissa":12, "roger":13, "Bob":12}

OrderedDict(sorted(d.items(), key=lambda x: (x[1], x[0])))
# dict(sorted(d.items(), key=lambda x: (x[1], x[0]))) # for Python 3.7
# [('Bob', 12), ('Mellissa', 12), ('roger', 13)]

Or you can also use operator.itemgetter to directly fetch the value and key from each tuple respectively:

OrderedDict(sorted(d.items(), key=itemgetter(1,0)))
# dict(sorted(d.items(), key=itemgetter(1,0))) # python 3.7
# [('Bob', 12), ('Mellissa', 12), ('roger', 13)]
like image 120
yatu Avatar answered Jan 08 '23 02:01

yatu