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