Sorting a `dictionary` in python

Many people think that sorting is not possible for dictionary, because they are not able to find a `.sort()` as in list for dictionary. Actually there is a function called `sorted()` which can be used to sort dictionary based on keys as well as values. Check the official python documentation for more details.

#! /usr/bin/python

a = {'one': 1, 'three': 3, 'four': 4, 'two': 2}
sorted(a.items(), key=lambda x: x[1])

# output [('one', 1), ('two', 2), ('three', 3), ('four', 4)]

Counting hashable objects

How can we count the number of occurance of alphabets in a string? As soon as this question hits, many of us starts to think about loops… But there is a better solution in python called ‘collections.Counter’

#! /usr/bin/python

import collections
the_string = 'sfsdfsdfsdfdsfsdfsdfsdfsdf'
results = collections.Counter(the_string)

# output
# Counter({'s': 9, 'f': 9, 'd': 8})

Check the official python documentation for more details.