1

I have a function:

def most_common(dictionary, integer):

'Integer' must be a positive number. This function must update the list to include the 'Integer' most common words in the dictionary.

For example

>>> def most_common({'ONE': 1, 'TWO': 2, 'THREE': 3}, 2)
>>> {'TWO' : 2, 'THREE' : 3}

The only code I have written for this function so far is to sort the dictionary.

dontworry123
  • 21
  • 1
  • 3

2 Answers2

3

If you want the most common words, use collections.Counter and its most_common method:

>>> import collections
>>> L = {'One' : 1, 'Two' : 2, 'Three' : 3}
>>> result = collections.Counter(L)
>>> dict(result.most_common(2)
{'Two': 2, 'Three': 3}
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
0
dict(sorted([(k,v) for k, v in L.items()], key=lambda x: x[1])[-2:])
gipsy
  • 3,859
  • 1
  • 13
  • 21