Reputation: 57
When I get "aabbbccde" as a input, I want to print
"b 3
a 2
c 2"
as an output. The latter is the number of occurrences in the string. I found solutions using 'collections.counter', but I want to solve using dictionaries. This is what I could come up with:
s = input()
a = {}
for i in s:
if i not in a:
a[i] = 1
else:
a[i] += 1
for j in sorted(a, key = itemgetter(a.values(), a.keys())):
print(j, a[j], end="\n")
also tried
for j in sorted(a, key = lambda a: a[1]):
print(j, a[j], end="\n")
Upvotes: 0
Views: 121
Reputation: 6234
dict(sorted(a.items(), key=lambda x: (x[1], -ord(x[0])), reverse=True))
This will create a dictionary sorted by descending values and the groups with the same values will be sorted by ascending keys.
Note: This will only work as long as the keys are single characters.
Upvotes: 1
Reputation: 2796
You were so close with the sorted key on the second attempt. since it's a dictionary, you need to get the value at that index as the key to sort. As Vishal noted, if you make the sorting key a tuple, you can sort by both count and character alphabetically.
The below will get the output only in order of most frequent occurrences to least. It ignores the character value, so they may show up in any order.
s = input()
a = {}
for i in s:
if i not in a:
a[i] = 1
else:
a[i] += 1
for j in sorted(a, key=lambda x: a[x], reverse=True):
print(j, a[j], end="\n")
with the input aabbbccde
that you put, this is the output, as expected:
b 3
a 2
c 2
d 1
e 1
Upvotes: 2