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'}
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.