0

I wrote this code to print out the dictionary items that are sorted in alphabetical order of the 'Keys' but i want to sort the 'Items' according to increasing/decreasing order of the numerical values of 'Dictionary Values'

Note: The result must contain item tuples of the form (key, Values) and the sorted order should be according to increasing/decreasing order of numerical 'Values'

def calculate(sentence):
sentence = sentence.lower()
d = {}
for characters in sentence:
    d[characters] = d.get(characters, 0) + 1
return sorted(d.items())


print(calculate("The quick brown fox jumps over the lazy dog"))

How can this be done? Please help me with this and if the solution is complex try explaining it as simple as possible. I'm only a beginner

For example: input = 'zzzzoopq' output = [('z', 4), ('o', 2), ('p', 1), ('q', 1)] (The output is sorted according to descending order of 'values')

1 Answers1

0

You can use defaultdicts and key/reverse arguments of sorted function:

from collections import defaultdict

def calculate(sentence):
    sentence = sentence.lower()
    d = defaultdict(int)
    for ch in sentence:
        d[ch] += 1
    return sorted(d.items(), key=lambda x: x[1], reverse=True)

calculate("The quick brown fox jumps over the lazy dog")
[(' ', 8),
 ('o', 4),
 ('e', 3),
 ('r', 2),
 ('u', 2),
 ('t', 2),
 ('h', 2),
 ('k', 1),
 ('l', 1),
 ('b', 1),
 ('q', 1),
 ('y', 1),
 ('w', 1),
 ('s', 1),
 ('v', 1),
 ('f', 1),
 ('p', 1),
 ('a', 1),
 ('j', 1),
 ('m', 1),
 ('i', 1),
 ('c', 1),
 ('z', 1),
 ('d', 1),
 ('x', 1),
 ('g', 1),
 ('n', 1)]
vurmux
  • 9,420
  • 3
  • 25
  • 45
  • Using [`collections.Counter`](https://docs.python.org/3/library/collections.html#collections.Counter) instead of `defaultdict(int)` would clean up the `calculate` function quite a bit. – 0x5453 Jun 10 '19 at 13:38