Files
30-seconds-of-code/snippets/frequencies.md
Azan Bin Zahid 9e76e8f67f Imrove frequencies snippet implementation (#234)
Co-authored-by: Isabelle Viktoria Maciohsek <maciv@hotmail.gr>
2020-10-03 16:50:18 +03:00

536 B

title, tags
title tags
frequencies list,intermediate

Returns a dictionary with the unique values of a list as keys and their frequencies as the values.

  • Use list.count() to get the frequency of each unique element.
  • Use dict() constructor to return a dictionary with the unique elements of the list as keys and their frequencies as the values.
def frequencies(lst):
  return dict((k, lst.count(k)) for k in lst)
frequencies(['a', 'b', 'a', 'c', 'a', 'a', 'b']) # { 'a': 4, 'b': 2, 'c': 1 }