From b047b8f546273b0dff5ef585ec00398b3450c9de Mon Sep 17 00:00:00 2001 From: Isabelle Viktoria Maciohsek Date: Sat, 14 Mar 2020 11:33:48 +0200 Subject: [PATCH] Add frequencies --- frequencies.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 frequencies.md diff --git a/frequencies.md b/frequencies.md new file mode 100644 index 000000000..f260e7353 --- /dev/null +++ b/frequencies.md @@ -0,0 +1,22 @@ +--- +title: frequencies +tags: list,intermediate +--- + +Returns a dictionary with the unique values of a list as keys and their frequencies as the values. + +Use a `for` loop to populate a dictionary, `f`, with the unique values in `lst` as keys, adding to existing keys every time the same value is encountered. + +```py +from functools import reduce + +def frequencies(lst): + f = {} + for x in lst: + f[x] = f[x] + 1 if x in f else 1 + return f +``` + +```py +frequencies(['a', 'b', 'a', 'c', 'a', 'a', 'b']) # { 'a': 4, 'b': 2, 'c': 1 } +```