Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

sort dict by value then if equal by keys

i created a dict, keys=words in list values=count of them. Want to sort them by counts(values) THEN if counts equal sort them by alpha(keys)

a = [to, be, or, not, to, be, ae, ae]
w={}
for i in a:
    w[i]=a.count(i)
e=dict(sorted(w.items(),key= lambda a: (a[1],a[0]),reverse=True))
for i, k in e.items():
    print(i , k)

what i get now is

to 2
be 2
ae 2
or 1
not 1

and what i want is

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ae 2
be 2
to 2
not 1
or 1 

im noob

>Solution :

reverse=true applies to both elements of the tuple. That why your alphanumeric output is backwards.

To reverse the order on the first element of the tuple but not on the other you could negate the numbers:

sorted(w.items(),key= lambda a: (-a[1],a[0]))

If you ever run into problem where you need to sort on multiple tuple elements with varying ASC/DESC order and elements that are not easy to negate like integers you could use the following technique.

Modified multisort from https://docs.python.org/3/howto/sorting.html#sort-stability-and-complex-sorts

Since the sorting is stable the following will work:

def multisort(xs, specs):
     for i, reverse in reversed(specs):
         xs.sort(key=lambda x: x[i], reverse=reverse)
     return xs

items = [('to', 2), ('be', 2), ('or', 1), ('not', 1), ('ae', 2)]
multisort(items, [(0, False), (1, True)])

Output:

[('ae', 2), ('be', 2), ('to', 2), ('not', 1), ('or', 1)]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading