Example 1: python ordereddict
>>>
>>> d = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2}
>>>
>>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])
>>>
>>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])
>>>
>>> OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))
OrderedDict([('pear', 1), ('apple', 4), ('orange', 2), ('banana', 3)])
Example 2: python counter
>>>
>>> cnt = Counter()
>>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
... cnt[word] += 1
>>> cnt
Counter({'blue': 3, 'red': 2, 'green': 1})
>>>
>>> import re
>>> words = re.findall(r'\w+', open('hamlet.txt').read().lower())
>>> Counter(words).most_common(10)
[('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631),
('you', 554), ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)]
Example 3: collections counter
import collections
arr = [1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3]
elements_count = collections.Counter(arr)
for key, value in elements_count.items():
print(f"{key}: {value}")
Example 4: python counting dictionary
counts = dict()
for i in items:
counts[i] = counts.get(i, 0) + 1
Example 5: python counter
sum(c.values())
c.clear()
list(c)
set(c)
dict(c)
c.items()
Counter(dict(list_of_pairs))
c.most_common()[:-n-1:-1]
c += Counter()