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?
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)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With