Programming tips

Sort a list based on custom key

Following is a list of employees in company with their ID and salary.

emp=[
    ['EMPCT01', 10000],
    ['EMPCT02', 20000],
    ['EMPCT03', 80000],
    ['EMPCT04', 30000]
]

How will you sort the emp in ascending order based on the salary. Ie, starting with the one with the lowest salary to the highest-paid one.

emp=[
    ['EMPCT01', 10000],
    ['EMPCT02', 20000],
    ['EMPCT04', 30000],
    ['EMPCT03', 80000]
]

Solution:

emp=[
    ['EMPCT01', 10000],
    ['EMPCT02', 20000],
    ['EMPCT03', 80000],
    ['EMPCT04', 30000]
]
emp.sort(key=lambda els: int(els[1]))
print(emp)

Multiply a string

Hey, you can multiply strings in Python.

print("Geekinsta " * 3)

Output:

Geekinsta Geekinsta Geekinsta

Python assignment expression

This is one of the major changes in Python 3.8 is the introduction of Assignment expressions. It is written using := and is known as “the walrus operator”. The classic style:

key = ''
while(key != 'q'):
    key = input("Enter a number or q to exit ")
    if key != 'q':
        print(int(key)**2)

Using assignment operators:

while((key:= input("Enter a number or q to exit ")) != 'q'):
    print(int(key)**2)

Python program to generate a list of numbers up to x

limit = int(input("Enter the limit: "))
l = [x for x in range(limit+1)]
print(l)

This is known as list comprehension. Output:

Enter the limit: 5
[0, 1, 2, 3, 4, 5]

Reverse of a string

x = "Hello World"
print(x[::-1])

Output:

dlroW olleH

Create a dictionary from two lists

We can combine the elements of two lists as key-value pairs to form a dictionary. Here’s an example.

keys = ['Name', 'age']
values = ['John', '22']

d = {k:v for k, v in zip(keys, values)}
print(d)

Virtualenv

Another important function of python is Virtualenv. Virtualenv means Virtual Environment. This, now my friends, is a very awesome function of python. Basically, to test python in different conditions, you would normally you would have to change the global python environment. But, one of the key benefits of sandboxing your python environment is that you can easily test one code under different python versions and package dependencies. To install virtualenv, you need to install pip first. You can do as follows: easy_install pip pip install virtualenv virtualenv python-workspace cd python-workspace source ./bin/activate python

Pip

Pip is something maybe most people know of. But still, it is awesome stuff that you need to know if you are starting with python. Sometimes, you need to inspect the source of a package before installing it. Most of the times, it’s for installing a newer version of some package. So, you can simply install pip and do the following:

pip install --download sqlalchemy_download sqlalchemy pip install --no-install sqlalchemy pip install --no-download sqlalchemy If you want to install the bleeding-edge version of a package, you can directly check it from the GIT repository. pip install git+https://github.com/simplejson/simplejson.git pip install svn+svn://svn.zope.org/repos/main/zope.interface/trunk

JSON-esque

Python has a lot of hidden stuff underneath. It only takes a person and his time to find out what all magical operators and stuff are hidden inside. One among all the other stuff is the famous JSON-esque. You can create nested dictionaries without explicitly creating sub-dictionaries. They magically come into existence as we reference them. Example as follows: users = tree() users['harold']['username'] = 'hrldcpr' users['handler']['username'] = 'matthandlersux' Now you can print the above as JSON with:

print(json.dumps(users)) And it will look like this {"harold": {"username": "hrldcpr"}, "handler": {"username": "matthandlersux"}}

Merging Python and Shell Scripts

Now, this is something you can’t do with C or C++. If you are an open-source guy, you would surely use Linux as the main Operating OS, or at least a Dual Boot. So, Linux already includes python. And python is extremely compatible with Linux. This gives us the benefit of compiling and merging them together. You can simply create a script that can work as a normal Unix script as well as an interpreted Python code at the same time. When writing a shell script, you need a four quote character and an empty string to the shell, but you need to do that with a triple-quoted string with a quote character in python. Remember that the first string in a script can be easily stored as a doc string for a module, but after that, the python interpreter will simply ignore it. An example is as follows: #!/bin/sh doc = """ Demonstrate how to mix Python + shell script. """ import sys print "Hello World!" print "This is Python", sys.version print "This is my argument vector:", sys.argv print "This is my doc string:", doc sys.exit (0)