supakeen's cheats

Python language

A bunch of commonly performed tasks that can be done quite tersely. Not always the best to use these for readability concerns but fun to take a look at or thing I have to look up.

Many of these examples make use of the itertools and functools built-in modules. I use some default naming such as L for list, D for dictionary.

Combining dictionaries

Creating a new dictonary:

{**D0, **D1}

Updating an existing dictionary:


Which one to use depends on your usecase.

Counting values in an iterable

Counting values of a certain type in ant iterable can be done in many ways, here are a few.

sum(value == "target" for value in L)

Or alternatively you could use:

sum(1 for value in L if value == "target")

Or use the builtin collections module:

import collections

Using a normal for loop and a collector variable is of course also possible!