1>>> from collections import Counter
2>>>
3>>> myList = [1,1,2,3,4,5,3,2,3,4,2,1,2,3]
4>>> print Counter(myList)
5Counter({2: 4, 3: 4, 1: 3, 4: 2, 5: 1})
6>>>
7>>> print Counter(myList).items()
8[(1, 3), (2, 4), (3, 4), (4, 2), (5, 1)]
9>>>
10>>> print Counter(myList).keys()
11[1, 2, 3, 4, 5]
12>>>
13>>> print Counter(myList).values()
14[3, 4, 4, 2, 1]
15
1>>> # regular unsorted dictionary
2>>> d = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2}
3
4>>> # dictionary sorted by key
5>>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))
6OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])
7
8>>> # dictionary sorted by value
9>>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))
10OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])
11
12>>> # dictionary sorted by length of the key string
13>>> OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))
14OrderedDict([('pear', 1), ('apple', 4), ('orange', 2), ('banana', 3)])
15
1# importing the collections module
2import collections
3# intializing the arr
4arr = [1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3]
5# getting the elements frequencies using Counter class
6elements_count = collections.Counter(arr)
7# printing the element and the frequency
8for key, value in elements_count.items():
9 print(f"{key}: {value}")
1>>> Counter('abracadabra').most_common(3)
2[('a', 5), ('r', 2), ('b', 2)]
3
1list = ["a","c","c","a","b","a","a","b","c"]
2cnt = Counter(list)
3od = OrderedDict(cnt.most_common())
4for key, value in od.items():
5 print(key, value)
6