Python tips

How to put all lines of a file into an array in Python ?

You can read a multiline file in different ways. Some of them are less verbose than the others and in this tip I will focus on one-line solution materializing the who le input at once. But let's begi...

Continue Reading β†’

How to use defaultdict in nested array in Python?

defaultdict helps to reduce boilerplate code in Python. Using it in normal circumstances is very easy: from collections import defaultdict default_int_dict = defaultdict(int) default_int_dict...

Continue Reading β†’

How to merge 2 dictionaries in Python?

There are multiple ways to achieve that but my favorite is the following: dict_1 = {'a': 10, 'b': 20, 'c': 30} dict_2 = {'c': 40, 'd': 50, 'e': 60} merged_dict = {dict_key: dict_1.get(dict_key,...

Continue Reading β†’

How to get a random element from an array in Python?

For a long time to access a random element in an array I used something like: import random letters = ['a', 'b', 'c', 'd'] random_letter = letters[random.randint(0, len(letters)-1)] assert r...

Continue Reading β†’

How to convert a dictionary into a list of tuples?

The goal is to transform a dictionary into a list of tuples where the key will be the first part of the tuple and the value the second part. To do this in Python we can use comprehensions: data = {...

Continue Reading β†’

How to create a time-aware Python cache without extra dependencies?

One of native methods supporting caching in Python is @lru_cache decorator. It caches method execution by parameters and it's the key of the solution proposed in this tip. Since the cache is parame...

Continue Reading β†’

How to unpack the middle of a collection in Python 3.5?

Let's suppose that we have a list like input_list = [1, 2, 3, 4, 5, 6] and we want to retrieve from it 3 variables, a=1, b=[2, 3, 4, 5] and c=6. A primitive solution to that problem could be: a, b,...

Continue Reading β†’

How to get first or last X values from a Python collection?

Python has an interesting method called slice. This function generates a slice which is a set of indices between start and stop every step elements. s: letters = ["a", "b", "c", "d", "e", "f", "g"]...

Continue Reading β†’

How to convert a defaultdict to dict in Python?

If for whatever reason you need a function returning a dictionary from a defaultdict, you can simply convert it that way: from collections import defaultdict default_int_dict = defaultdict(int) ...

Continue Reading β†’