collections.counter in python
>>> from collections import Counter
>>>
>>> myList = [1,1,2,3,4,5,3,2,3,4,2,1,2,3]
>>> print Counter(myList)
Counter({2: 4, 3: 4, 1: 3, 4: 2, 5: 1})
>>>
>>> print Counter(myList).items()
[(1, 3), (2, 4), (3, 4), (4, 2), (5, 1)]
>>>
>>> print Counter(myList).keys()
[1, 2, 3, 4, 5]
>>>
>>> print Counter(myList).values()
[3, 4, 4, 2, 1]
An OrderedDict is a dictionary subclass that remembers the order
that keys were first inserted. A regular dict doesn’t track the
insertion order, and iterating it gives the values in an arbitrary
order.
# A Python program to demonstrate working of OrderedDict
from collections import OrderedDict
d = {} # regular dict
d['a'] = 1
d['b'] = 2
d['c'] = 3
for key, value in d.items():
print(key, value)
# Output
# ('a', 1)
# ('c', 3)
# ('b', 2)
od = OrderedDict() # Ordered Dict
od['a'] = 1
od['b'] = 2
od['c'] = 3
for key, value in od.items():
print(key, value)
# Output
# ('a', 1)
# ('b', 2)
# ('c', 3)
>>> # regular unsorted dictionary
>>> d = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2}
>>> # dictionary sorted by key
>>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])
>>> # dictionary sorted by value
>>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])
>>> # dictionary sorted by length of the key string
>>> OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))
OrderedDict([('pear', 1), ('apple', 4), ('orange', 2), ('banana', 3)])