Python tips

Pass dictionary items as a parameter

The key-value pairs of a dictionary can be directly passed as named parameters to any function in the same way we passed a list before.

d = {'age': 25, 'name': 'Jane'}

def showdata(name, age):
    print(f'{name} is {age} years old')

showdata(**d)

Using two lists in a loop

We normally use the range() function or an inerrable object to create a for loop. We can also create a for loop with multiple interactable objects using the zip() function.

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

for i, j in zip(keys, values):
    print(f'{i}: {j}')

Interchanging keys and values of a Dictionary

Python allows you to easily swap the keys and values of a dictionary using the same syntax we use for dictionary comprehension. Here’s an example.

d = {1: 'One', 2: 'Two', 3: 'Three'}
di = { v:k for k, v in d.items()}
print(di)

Flatten a list of lists

Usually, we flatten a list of lists using a couple of nested for loops. Although this method works fine, it makes our code larger. So, here’s a shorter method to flatten a list using the itertools module.

import itertools
a = [[1, 2], [3, 4]]
b = list(itertools.chain.from_iterable(a))
print(b)

Pass list items as arguments

In Python, you can pass the elements of a list as individual parameters without specifying it manually by index using the * operator. This is also known as unpacking.

l = [5, 6]
def sum(x, y):
    print(x + y)

sum(*l)

Create string from a list

With the join method Python, we can easily convert the items of a list to string.

l = ['Join', 'this', 'string']
print(str.join(' ', l))

Shuffle the items of a list

How do you usually shuffle the items in a list? Most of the Python beginners will be using a loop to iterate over the list and shuffle the items. But python has an inbuilt method to shuffle list items. To use this method, we should first import random module.

from random import shuffle
l = [1, 2, 3]
shuffle(l)
print(l)

You will get different outputs each time you run the code.

Check if a string exists in another string

There are several methods to do this.

x = "Hi from Geekinsta"
substr = "Geekinsta"

# Method 1
if substr in x:
    print("Exists")

# Method 2
if x.find(substr) >=0:
    print("Exists")

# Method 3
if x.__contains__(substr):
    print("Exists")

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