0

I have a Dictionary that, when printed with each key and value, looks like this:

a__________a_______:1
___________________:2
_______________a___:1
___________a____a__:1
___________a_a_____:1
__________a__a_____:1
________a______a___:1
____a____________a_:1
_____a_____________:1
__a_______a________:1
__________a________:2
____________a____a_:2
_______a___________:1

I am trying to sort the dictionary so that it is sorted by value, which is pretty simple. However, each group within the same value has to be sorted by the number of '_'s; and if the number of underscores is the same, then they are sorted alphabetically. So, after sorting, it would look like this:

___________a____a__:1
___________a_a_____:1
__________a__a_____:1
________a______a___:1
____a____________a_:1
__a_______a________:1
a__________a_______:1
_______________a___:1
_______a___________:1
_____a_____________:1
____________a____a_:2
__________a________:2
___________________:2

I understand sorting by value. I am just having trouble being able to sort it within each value group like I stated.

  • 2
    I don't know well about python, but this might help : https://stackoverflow.com/questions/20145842/python-sorting-by-multiple-criteria?lq=1 – Chan Kim Dec 15 '20 at 01:49

1 Answers1

0

You can sort using a tuple in order of your desired means of ordering:

res = dict(sorted(d.items(), key=lambda it: (it[1], it[0].count('_'), it[0])))
ssp
  • 1,666
  • 11
  • 15