How to Sort a Dictionary by Value in Python

I have implemented the sorting of dictionary using the for loop and lambda function using the Test Driven Data / TDD approach.
Here is the simple code.

@Author: Aseem Jain

Sort map/dictionary by keys and values


def sol(m):
    s_k ={}
    s_v ={}
    # On 1
    for k in sorted(m.keys()):
        s_k[k] = m.get(k)

    for v in sorted(m.values()):
        for k in m:
            if v == m.get(k):
                s_v[k] = v

    return (s_k,s_v)

def sol1(m):
    s_k_t = sorted(m.items(),key=lambda i:i[0])
    s_v_t = sorted(m.items(),key=lambda i:i[1])

    s_k_m = {}
    for k,v in s_k_t: s_k_m[k]=v

    s_v_m = {}
    for k,v in s_v_t: s_v_m[k]=v

    return (s_k_m,s_v_m)

def sol2(m):
    s_k_t = sorted(m.items(),key=lambda i:i[0])
    s_v_t = sorted(m.items(),key=lambda i:i[1])
    def tuple_to_map(t):
        new_m = {}
        for k,v in t:
        return new_m
    return (tuple_to_map(s_k_t),tuple_to_map(s_v_t))

# Test with given map and expected sorted values 
map = { 3:15, 0:10, 5:50, 7:25 }
sorted_key = { 0:10, 3:15, 5:50, 7:25 }
sorted_values = { 5:50, 7:25, 0:10, 3:15}

test_data = [
    (map, (sorted_key,sorted_values) )

for given, expected in test_data:
    assert sol(given) == expected
    assert sol1(given) == expected
    print(f"Test passed for: given {given} and expected = {expected}")

User defined custom object sorting in python

@Author: Aseem Jain

Title: Sort the class or custom object and not regular int / string using in build sort funcitons
Sort custom object can be done in 2 ways
1. Static way : class implementing < less then __lt__(self,other)
2. Dynamic way is by providing lambda func with key.
class User:
def __init__(self,name,age): = name
self.age = age

def __repr__(self):
return + str(self.age)

def __lt__(self, other):
return self.age < other.age

# Sorting String
ls = ["zeema", "aseemjain", "see",str(3),str(13),"$$"]
#output: ['$$', '3', 'aseemjain', 'see', 'zeema']

# Reverse soring
# output: ['zeema', 'see', 'aseemjain', '3', '$$']

# sorting Custom object
users = [User("aseem",16),User("aseemprem",56),User("premaseem",23),User("zseem",36),User("nseem",106) ]
users.sort(key = lambda x:
# output : [aseem16, aseemprem56, nseem106, premaseem23, zseem36]

# create new sorted list
newlist = sorted(users, key=lambda x: x.age, reverse=True)
# output: [nseem106, aseemprem56, zseem36, premaseem23, aseem16]

Github link:

Python: Check if all elements in a list are equal

# Pythonic ways of checking if all
# items in a list are equal:

>>> lst = ['a', 'a', 'a']

>>> len(set(lst)) == 1

>>> all(x == lst[0] for x in lst)

>>> lst.count(lst[0]) == len(lst)

# I ordered those from "most Pythonic" to "least Pythonic" 
# and  "least efficient" to "most efficient". 
# The len(set()) solution is idiomatic,  but constructing 
# a set is less efficient memory and speed-wise.

Python: Dict get with default value to void key not found error

# The get() method on dicts
# and its "default" argument

name_for_userid = {
    382: "Aseem",
    590: "Bob",
    951: "Dilbert",

def greeting(userid):
    return "Hi %s!" % name_for_userid.get(userid, "there")

>>> greeting(382)
"Hi Aseem!"

>>> greeting(333333)
"Hi there!"

Python: emulate switch/case statements by using dict with lambda functions

# Because Python has first-class functions they can
# be used to emulate switch/case statements

def dispatch_if(operator, x, y):
    if operator == 'add':
        return x + y
    elif operator == 'sub':
        return x - y
    elif operator == 'mul':
        return x * y
    elif operator == 'div':
        return x / y
        return None

def dispatch_dict(operator, x, y):
    return {
        'add': lambda: x + y,
        'sub': lambda: x - y,
        'mul': lambda: x * y,
        'div': lambda: x / y,
    }.get(operator, lambda: None)()

>>> dispatch_if('mul', 2, 8)

>>> dispatch_dict('mul', 2, 8)

>>> dispatch_if('unknown', 2, 8)

>>> dispatch_dict('unknown', 2, 8)

Python : List of Python Tutorials

If you are looking for a single list of python tutorial, then you landed on a very good blog post.

Learn Python online – A curated list of courses on Python

Here is the link :

This will allow you to try our different python courses available online.

Python : How to set a global variable in a function

x = 1 # make a global module variable

def f():
      print x # try to print the global
      for j in range(100):
           if q > 3:

Any variable assigned in a function is local to that function, unless it is specifically declared global. Since a value is bound to x as the last statement of the function body, the compiler assumes that x is local. Consequently the “print x” statement attempts to print an uninitialized local variable and will trigger aUnboundLocalError (or in earlier Python versions, a NameError).

The solution is to insert an explicit global declaration at the start of the function:

def f():
      global x
      print x # try to print the global
      for j in range(100):
           if q > 3:

In this case, all references to x are interpreted as references to the x from the module namespace.

Note that the global declarations must be placed at the beginning of the function, and that it affects all uses of the variable inside the function.

API : Profanity alert api by google –

This is a cool api to check the profane words in contents. It could be used to scan emails, documents and even public comments on your blog 🙂

A simple and sweet sample program to understand and consume it.

__author__ = 'premaseem'
import urllib

# file reader functions
def read_file():
    doc= open('/Users/asee2278/gitRepo/petProjects/python_mini_projects/Profinity_alert/document.txt')
    contents =
    print contents
    return contents

# function with google api to check profanity in contents
def check_contenct_profanity(contents):
    connection = urllib.urlopen(''+contents)
    output =
    print output
    if 'true' in output :
        print " Profanity Alert !! "
    elif 'false' in output :
        print " This document has not curse words :-)"
    else :
        print "sorry could not scan the doc "

# read the file and grab contents
contents = read_file()

# check for profanity

Python : What is pip or PyPi

pip is a package management system used to install and manage software packages written in Python. Many packages can be found in thePython Package Index (PyPI).

All the major supported packages / modules in python are hosted and listed at site called as Pypi Python Index – with pre-registered name. User can install / uninstall any package with its respective version using pip.

One major advantage of pip is the ease of its command-line interface, which makes installing Python software packages as easy as issuing one command:

pip install some-package-name

Users can also easily remove the package:

pip uninstall some-package-name

Most importantly pip has a feature to manage full lists of packages and corresponding version numbers, possible through a “requirements” file.This permits the efficient re-creation of an entire group of packages in a separate environment (e.g. another computer) or virtual environment. This can be achieved with a properly formatted requirements.txt file and the following command:

pip install -r requirements.txt

Install some package for a specific version python, where ${version} is replaced for 2, 3, 3.4, etc:

pip${version} install some-package-name

Python : What is Virtual Environment

Each project might need some set of dependencies with their specific version to work properly. Usually, we might have multiple projects running on different versions / packages. For example

  • some project on python2 others python 3
  • some project using pymongo2.7 others pymongo3.2

Normally, we have installed python 2.7, then we might not run python3 without upgrading to python3, however there is solution called virtual Environment which allows us to have an environment for specific required for each project and it is called as virtual environment. This can be installed using below command

$ [sudo] pip install virtualenv

The trick is to create separate folder for each project and activate virtual environment over there, that way requirements might not clash with each other. 

for example, i have 2 projects named make_money and spend_money wh

So I have to make 2 different directories and install virtual environment in them, I can run my project from any where, however the dependencies would be installed in that specific project. 

It is kind of similar to NPM for node, and pip is similar to maven in java

Helpful link :