atifcppprogrammer
atifcppprogrammer

Reputation: 132

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?

Upvotes: 4

Views: 3103

Answers (2)

yatu
yatu

Reputation: 88246

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)]

Upvotes: 7

blhsing
blhsing

Reputation: 106792

You can sort the dict items with a key function that reverses the order of the key-value tuple:

dict(sorted(pyDictionary.items(), key=lambda t: t[::-1]))

Upvotes: 2

Related Questions