Python is a programming language used by a lot of developers around the world. It was released in 1991 and it is
one of the most popular programming languages.
Python is used by a lot of data scientists, data engineers and machine learning engineers, basically everybody
who is
dealing with data and AI. It has specific libraries for machine learning such as Scikit-learn, Keras,
Tensorflow, PyTorch and much more.
The first hack is merging two dictionaries in Python.
In python 3.5 or greater, we can use the following method.
dict_1 = {"a": "1", "b": "2", "c": "3"}
dict_2 = {"z": "10", "y": "11"}
merged_dict = {**dict_1, **dict_2}
merged_dict
>> {'a': '1', 'b': '2', 'c': '3', 'z': '10', 'y': '11'}
This is a very simple and convenient method to merging two dictionaries.
This wonderful hack is for measuring the execution time of a program or a simple python script.
import time
start_time = time.time()
## Our Program
##
time.time() - start_time
We put our program or our script between the "## Our Program" and "##" then we get the value of time.time()-start_time which represents the execution time of our program. Very simple and very convenient.
We can sort lists by alphabetical order or numerical order by using the function Sorted().
list_1 = [595, 2, 6, 1]
list_2 = ["m", "d", "c", "p"]
sorted(list_1)
sorted(list_2)
>> [1, 2, 6, 595]
>> ['c', 'd', 'm', 'p']
We can copy any list we want by using the function Copy().
list_1 = [595, 2, 6, 1]
new_list = list_1.copy()
new_list
>> [595, 2, 6, 1]
I got introduced to this hack by a colleague. it's extremely effective when dealing with a lot of data and it's
so much better than a normal Print() function.
If you want to print your data structures in a more organized way, then you should use the function Pprint()
after importing it.
from pprint import pprint
data = {"a": {595, 2, 6, 1}, "b":{"m", "d", "c", "p"}, "c": {595, 2, 6,1}, "d": {"m", "d", "c", "p"}}
pprint(data)
>> {'a': {1, 2, 595, 6},
'b': {'d', 'm', 'p', 'c'},
'c': {1, 2, 595, 6},
'd': {'d', 'm', 'p', 'c'}}
Using a normal Print() function in the example in the image above will print the whole data in a single line of text which is not very convenient specially when, once again, dealing with a lot of data.
Those were some of my favorite Python Hacks ! I hope you have found them useful as well.
If you have any questions or wants to know more about the article,
feel free to email me or
tweet at me!