11 Bite-Sized Python Recipes You Must Know

11 Bite-Sized Python Recipes You Must Know

Originally posted on makeuseof.

These code samples will help you learn about Python basics and solve common everyday challenges.

Many programmers like Python for its simple and concise syntax. These Python recipes are small sample programs that you can use to solve common daily problems.

Use these easy-to-digest Python recipes and take your coding efficiency to the next level.

1. Extract a Subset of a Dictionary

You can extract a subset of a dictionary using the dictionary comprehension method.

test_marks = {
 'Alex' : 50,
 'Adam' : 43,
 'Eva' : 96,
 'Smith' : 66,
 'Andrew' : 74
}
 
greater_than_60 = { key:value for key, value in test_marks.items() if value > 60 }
print(greater_than_60)
 
students = { 'Alex', 'Adam', 'Andrew'}
a_students_dict = { key:value for key,value in test_marks.items() if key in students }
print(a_students_dict)

Output:

{'Eva': 96, 'Smith': 66, 'Andrew': 74}
{'Alex': 50, 'Adam': 43, 'Andrew': 74}

2. Search and Replace Text

You can search and replace a simple text pattern in a string using the str.replace() method.

str = "Peter Piper picked a peck of pickled peppers"
str = str.replace("Piper", "Parker")
print(str)

Output:

Peter Parker picked a peck of pickled peppers

For more complicated patterns, you can use the sub() method from the re library. Regular Expressions in Python make the task a lot easier for complicated patterns.

import re
str = "this is a variable name"
result = re.sub('\⁠s', '_', str)
print(result)

Output:

this_is_a_variable_name

The above code replaces the white-space character with an underscore character.

3. Filter Sequence Elements

You can filter elements from a sequence according to certain conditions using list comprehension.

list = [32, 45, 23, 78, 56, 87, 25, 89, 66]
 
# Filtering list where elements are greater than 50
filtered_list = [ele for ele in list if ele>50]
print(filtered_list)

Output:

[78, 56, 87, 89, 66]

4. Align Text Strings

You can align text strings using the ljust()rjust(), and center() methods. These methods left-justify, right-justify, and center a string in a field of a given width.

str = "Python is best"
print(str.ljust(20))
print(str.center(20))
print(str.rjust(20))

Output:

Python is best 
 Python is best 
 Python is best

These methods also accept an optional fill character.

str = "Python is best"
print(str.ljust(20, '#'))
print(str.center(20, '#'))
print(str.rjust(20, '#'))

Output:

Python is best######
###Python is best###
######Python is best

Note: You can also use the format() function to align strings.

5. Convert Strings Into Datetimes

You can use the strptime() method from the datetime class to convert a string representation of the​ date/time into a date object.

from datetime import datetime
str = '2022-01-03'
print(str)
print(type(str))
datetime_object = datetime.strptime(str, '%Y-%m-%d')
print(datetime_object)
print(type(datetime_object))

Output:

2022-01-03
<class 'str'>
2022-01-03 00:00:00
<class 'datetime.datetime'>

Note: If the string argument is not consistent with the format parameter, the strptime() method will not work.

6. Unpack a Sequence Into Separate Variables

You can unpack any sequence into variables using the assignment operation. This method works as long as the number of variables and the structure of the sequence match with each other.

Unpacking Tuples

tup = (12, 23, 34, 45, 56)
a, b, c, d, e = tup
print(a)
print(d)

Output:

12
45

Unpacking Lists

list = ["Hey", 23, 0.34, (55, 76)]
a, b, c, d = list
print(a)
print(d)

Output:

Hey
(55, 76)

Unpacking Strings

str = "Hello"
ch1, ch2, ch3, ch4, ch5 = str
print(ch1)

Output:

H

If the number of variables and the structure of the sequence mismatch, you’ll get an error:

list = ["Hey", 23, 0.34, (55, 76)]
a, b, c = list

Output:

Traceback (most recent call last):
File "unpack-list-error.py", line 2, in <module>
a, b, c = list
ValueError: too many values to unpack (expected 3)

7. Writing Functions That Accept Any Number of Positional Arguments

You need to use a * argument to accept any number of positional arguments.

def sumOfElements(firstTerm, *otherTerms):
 s = firstTerm + sum(otherTerms)
 print(s)
sumOfElements(10, 10, 10, 10, 10)
sumOfElements(10)
sumOfElements(10, 10, 10)

Output:

50
10
30

8. Return Multiple Values from a Function

You can return multiple values from a function using a tuple, list, or dictionary.

def returnMultipleSports():
 sport1 = "football"
 sport2 = "cricket"
 sport3 = "basketball"
 return sport1, sport2, sport3
sports = returnMultipleSports()
print(sports)

Output:

('football', 'cricket', 'basketball')

In the above example, the function returns a tuple. You can unpack the tuple and use the returned values.

def returnMultipleLanguages():
 language1 = "English"
 language2 = "Hindi"
 language3 = "French"
 return [language1, language2, language3]
languages = returnMultipleLanguages()
print(languages)

Output:

['English', 'Hindi', 'French']

In this example, the function returns a list.

9. Iterate in Reverse

You can iterate over a sequence in reverse order using the reversed() function, range() function, or using the slicing technique.

Iterating in Reverse Using the reversed() Function

list1 = [1, 2, 3, 4, 5, 6, 7]
for elem in reversed(list1):
 print(elem)

Output:

7
6
5
4
3
2
1

Iterating in Reverse Using the range() Function

list1 = [1, 2, 3, 4, 5, 6, 7]
for i in range(len(list1) - 1, -1, -1):
 print(list1[i])

Output:

7
6
5
4
3
2
1

Iterating in Reverse Using the Slicing Technique

list1 = [1, 2, 3, 4, 5, 6, 7]
for elem in list1[::-1]:
 print(elem)

Output:

7
6
5
4
3
2
1

10. Reading and Writing JSON to a File

You can work with JSON data using the built-in json package in Python.

Writing JSON to a File

You can write JSON to a file using the json.dump() method.

import json
languages = {
 "Python" : "Guido van Rossum",
 "C++" : "Bjarne Stroustrup",
 "Java" : "James Gosling"
}
with open("lang.json", "w") as output:
 json.dump(languages, output)

This will create a new file named lang.json.

Reading JSON From a File

You can read JSON from a file using the json.load() function. This function loads the JSON data from a JSON file into a dictionary.

import json
with open('lang.json', 'r') as o:
 jsonData = json.load(o)
print(jsonData)

Output:

{'Python': 'Guido van Rossum', 'C++': 'Bjarne Stroustrup', 'Java': 'James Gosling'}

11. Writing to a File That Doesn’t Already Exist

If you want to write to a file only if it doesn’t already exist, you need to open the file in x mode (exclusive creation mode).

with open('lorem.txt', 'x') as f:
 f.write('lorem ipsum')

If the file lorem.txt already exists, this code will cause Python to throw a FileExistsError.

If you want to have a look at the complete source code used in this article, here’s the GitHub repository.

Make Your Code Robust With Built-In Python Functions

Use functions to break a program into modular chunks and perform specific tasks. Python provides many built-in functions like range(), slice(), sorted(), abs(), and so on that can make your tasks a lot easier. Make use of these built-in functions to write a more readable and functional code.

 

Source: makeuseof