Files
30-seconds-of-code/snippets/frequencies.md
Isabelle Viktoria Maciohsek 6d52040e37 Update frequencies.md
2020-10-16 20:37:50 +03:00

24 lines
620 B
Markdown

---
title: frequencies
tags: list,intermediate
---
Returns a dictionary with the unique values of a list as keys and their frequencies as the values.
- Use `collections.defaultdict()` to store the frequencies of each unique element.
- Use `dict()` to return a dictionary with the unique elements of the list as keys and their frequencies as the values.
```py
from collections import defaultdict
def frequencies(lst):
freq = defaultdict(int)
for val in lst:
freq[val] += 1
return dict(freq)
```
```py
frequencies(['a', 'b', 'a', 'c', 'a', 'a', 'b']) # { 'a': 4, 'b': 2, 'c': 1 }
```