Python CookBook
Sure, here are some fundamental Python “recipes” you might find useful.
- Reading a File
with open('myfile.txt', 'r') as f:
data = f.read()
- Writing to a File
with open('myfile.txt', 'w') as f:
f.write("Hello, world!")
- Sorting a List of Dictionaries by a Common Key
from operator import itemgetter
list_of_dicts = [{'name': 'John', 'age': 25}, {'name': 'Jane', 'age': 23}, {'name': 'Dave', 'age': 30}]
sorted_list = sorted(list_of_dicts, key=itemgetter('age'))
- Creating a Dictionary from Two Lists
keys = ['name', 'age', 'job']
values = ['John', 25, 'developer']
dict_from_lists = dict(zip(keys, values))
- Catching Exceptions
try:
# risky operation
risky_operation()
except Exception as e:
print(f"Caught an exception: {e}")
- Creating a Function with Optional Arguments
def my_function(a, b, c=None):
if c is None:
c = []
# do something
- Iterating Over a List with Indices
my_list = ['apple', 'banana', 'cherry']
for i, value in enumerate(my_list):
print(f"Item {i} is {value}")
- List Comprehensions
squares = [x**2 for x in range(10)]
- Lambda Functions
f = lambda x: x**2
print(f(5)) # prints 25
- Filtering Items in a List
my_list = [1, 2, 3, 4, 5]
filtered_list = list(filter(lambda x: x % 2 == 0, my_list)) # [2, 4]
- Using
map
to Apply a Function to All Items in a List
my_list = [1, 2, 3, 4, 5]
squared_list = list(map(lambda x: x**2, my_list)) # [1, 4, 9, 16, 25]
Remember that Python is a highly flexible language, and there are often many ways to achieve the same result. These are some idiomatic examples, but other approaches could also be valid.
Python Training Demo Day 1
Conclusion:
Unogeeks is the No.1 IT Training Institute for Python Training. Anyone Disagree? Please drop in a comment
You can check out our other latest blogs on Python here – Python Blogs
You can check out our Best In Class Python Training Details here – Python Training
Follow & Connect with us:
———————————-
For Training inquiries:
Call/Whatsapp: +91 73960 33555
Mail us at: info@unogeeks.com
Our Website ➜ https://unogeeks.com
Follow us:
Instagram: https://www.instagram.com/unogeeks
Facebook: https://www.facebook.com/UnogeeksSoftwareTrainingInstitute
Twitter: https://twitter.com/unogeeks