Useful Python Tips

Introduction

Python has various convenient mechanisms of problem-solving, we can solve many problems using just one line of code, please refer to this article.

This article covers more such convenient tricks of problem-solving using Python core library functions or which can be achieved using other Python-based libraries like Pandas, NumPy, etc. Let’s explore.

Converting a CSV to Excel

Using Pandas, it’s just a 3-step process to convert the .csv file to excel, first, the dataframe should be created by reading the CSV file, then the dataframe has method to_excel which be utilized for the conversion, below code does that

import pandas as pd 
df = pd.read_csv('Employees.csv')
df.to_excel('Employees_excel.xlsx', sheet_name='Employee Details')

Representing data from CSV to HTML

Again, this can be done using the Pandas library, the dataframe object has a method to_html which can be used for the conversion of CSV data to HTML

import pandas as pd 
df = pd.read_csv('Employees.csv')
df.to_html('Employee.html')

Useful Python Tips

Awesome, isn’t it.

Repeating String

The String can be represented without looping using Python with the help of the '*' operator

name = "a"
print(name * 4)
#results in aaaa 

Checking the memory usage

The sys module has a method ‘getsizeof’ which displays the memory consumed by an object. The getsizeof method returns the size of an object in bytes.

import sys 
name = "David"
print(sys.getsizeof(name))
# 54

Merging dictionaries

Say we have 2 dictionaries, and we want to merge them

one = {"name":"David", "age": 32}
two = {"dept":"IT", "Location": "TX"}
merged = {** one, ** two}
merged
# returns {'name': 'David', 'age': 32, 'dept': 'IT', 'Location': 'TX'}

If the dictionaries have same keys

one = {"name":"David", "age": 32}
two = {"name":"David", "age": 33, 'lastname': 'P'}
merged = {** one, ** two}
merged
# returns {'name': 'David', 'age': 33, 'lastname': 'P'}

If there are three dictionaries, they can be merged using the same syntax

one = {"name":"David", "age": 32}
two = {"dept":"IT", "Location": "TX"}
three = {"Designation" : "Engineer"}
merged = {** one, ** two, ** three}
merged
# returns {'name': 'David', 'age': 32, 'dept': 'IT', 'Location': 'TX', 'Designation': 'Engineer'}

Using getpass for passwords

The getpass helps in hiding the user passwords on the console.

from getpass import getpass
user = input('user : ')
password = getpass('password : ')

Upon entering

Summary

The article is an extension of the earlier article, which is mentioned in the Introduction section. In this article, we have covered some of the important Python tricks and techniques like getpass, conversion of CSV to excel, CSV to HTML, etc. There are many such techniques in Python that we will keep covering.


Similar Articles