As I'm using Python for every day tasks, I find myself repeating some tasks over and over again. Here I present a collection of code snippets for the usually performed tasks, so you can use them straight ahead in your project whenever you need them and speed up your implementation. All snippets are related to general-purpose snippets that you can use for any application.
Sort dictionary according to a desired order list
sample_dict = {'1': 'Item 1', '2': 'Item 2', '3': 'Item 3', '4': 'Item 4', '5': 'Item 5'}
desired_order_list = ['3', '2', '1', '5', '4']
reordered_dict = { k: sample_dict[k] for k in desired_order_list }
The reordered_dict is: {'3': 'Item 3', '2': 'Item 2', '1': 'Item 1', '5':
'Item 5', '4': 'Item 4'}
Find duplicates in a list
Given a list with potentially repeated items, we want to find which elements appear more than once. This snippet uses a list comprehension and set to extract all duplicates without repetition.
items = [1, 2, 2, 3, 4, 4, 5]
duplicates = list(set([x for x in items if items.count(x) > 1]))
The duplicates
is: [2, 4]
Flatten a nested list
When you have a list of lists (a nested list), this script flattens it into a single list containing all the elements in order. It’s useful for simplifying nested structures into one continuous list.
nested = [[1, 2], [3, 4], [5]]
flat = [item for sublist in nested for item in sublist]
The flat
is: [1, 2, 3, 4, 5]
Count frequency of elements in a list
This snippet counts how many times each element appears in a list, returning a dictionary-like object (Counter) where keys are the items and values are their counts. Perfect for quick frequency analysis.
from collections import Counter
lst = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
freq = Counter(lst)
The freq
is: Counter({'apple': 3, 'banana': 2, 'orange': 1})
Merge two lists into a dictionary
We have two lists in Python and we want to merge them in a dictionary, where one
list's (keys_list
) items will act as the dictionary's keys and the
other's (values_list
) as the values.
keys_list = ['a', 'b', 'c']
values_list = ['red', 'green', 'blue']
new_dict = dict(zip(keys_list, values_list))
The new_dict
is: {'a': 'red', 'b': 'green', 'c': 'blue'}
Cartesian product of lists
Suppose there are two lists: ['a', 'b', 'c'], ['1', '2', '3'] and we want this: ['a1','a2','a3','b1','b2','b3','c1','c2','c3']. This concept is called a Cartesian product, and the stdlib itertools.product will build one for you.
from itertools import product
list_1 = ['a','b','c']
list_2 = ['1','2','3']
product = list(map(''.join, product(list_1, list_2)))
The product
is: ['a1', 'a2', 'a3', 'b1', 'b2', 'b3', 'c1', 'c2', 'c3']
.
Sort a list of dictionaries
Another frequent task is when we have two or more lists, and we want to collect them all in one big list of lists, where all the first items of the smaller list form the first list in the bigger list.
from operator import itemgetter
list_of_dicts = [
{ "student": "A", "grade": 15, },
{ "student": "B", "grade": 20, },
{ "student": "C", "grade": 18, }
]
sorted_list_of_dicts = sorted(list_of_dicts, key=itemgetter('grade'))
The sorted_list_of_dicts
is: [{ "student": "B", "grade": 20, }, {
"student": "C", "grade": 18, },{ "student": "A", "grade": 15}]
.
By default the order of sorting is ascending. If you want to sort the list in
descending order you should use the additional argument
reverse=True
in the 'sorted' function.