Last active
February 16, 2024 12:24
-
-
Save ronakjain2012/de485b3690c78935e302e8b0dfa1dcf2 to your computer and use it in GitHub Desktop.
Python Snippets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Formatting strings with f string. | |
str_val = 'books' | |
num_val = 15 | |
print(f'{num_val} {str_val}') # 15 books | |
print(f'{num_val % 2 = }') # 1 | |
print(f'{str_val!r}') # books | |
#Dealing with floats | |
price_val = 5.18362 | |
print(f'{price_val:.2f}') # 5.18 | |
#Formatting dates | |
from datetime import datetime; | |
date_val = datetime.utcnow() | |
print(f'{date_val=:%Y-%m-%d}') # date_val=2021-09-24 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import defaultdict | |
#merge two or more dicts using the collections module | |
def merge_dicts(*dicts): | |
mdict = defaultdict(list) | |
for d in dicts: | |
for key in d: | |
mdict[key].append(d[key]) | |
return dict(mdict) | |
print(merge_dicts({'a':'One','c':'Three','f':{'g':'Five'}},{'b':'Two'})) | |
# {'a': ['One'], 'c': ['Three'], 'f': [{'g': 'Five'}], 'b': ['Two']} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def merge(*args, missing_val = None): | |
#missing_val will be used when one of the smaller lists is shorter tham the others. | |
#Get the maximum length within the smaller lists. | |
max_length = max([len(lst) for lst in args]) | |
outList = [] | |
for i in range(max_length): | |
outList.append([args[k][i] if i < len(args[k]) else missing_val for k in range(len(args))]) | |
return outList | |
out = merge([1,2,3], ['a','b','c','z'], ['h','e','y'], missing_val='XXX') | |
print(out) | |
# [[1, 'a', 'h'], [2, 'b', 'e'], [3, 'c', 'y'], ['XXX', 'z', 'XXX']] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
dicts_lists = [ | |
{ | |
"Name": "James", | |
"Age": 20, | |
}, | |
{ | |
"Name": "May", | |
"Age": 14, | |
}, | |
{ | |
"Name": "Katy", | |
"Age": 23, | |
} | |
] | |
#There are different ways to sort that list | |
#1- Using the sort/ sorted function based on the age | |
dicts_lists.sort(key=lambda item: item.get("Age")) | |
#2- Using itemgetter module based on name | |
from operator import itemgetter | |
f = itemgetter('Name') | |
dicts_lists.sort(key=f) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
a = ['blue', 'green', 'orange', 'purple', 'yellow'] | |
b = [3, 2, 5, 4, 1] | |
#Use list comprehensions to sort these lists | |
sortedList = [val for (_, val) in sorted(zip(b, a), key=lambda x: \ | |
x[0])] | |
print(sortedList) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
my_list = ["blue", "red", "green"] | |
#1- Using sort or srted directly or with specifc keys | |
my_list.sort() #sorts alphabetically or in an ascending order for numeric data | |
my_list = sorted(my_list, key=len) #sorts the list based on the length of the strings from shortest to longest. | |
# You can use reverse=True to flip the order | |
#2- Using locale and functools | |
import locale | |
from functools import cmp_to_key | |
my_list = sorted(my_list, key=cmp_to_key(locale.strcoll)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment