Python Code Snippets

Dunston

Registered Member
Joined
Mar 4, 2023
Messages
64
Reaction score
42
In the spirit of contributing something to this community, I've compiled a collection of code snippets to share. These are meant to be reference material for anyone interested, but there are also code snippets that I have used in real life at one point or another. Hoping others might contribute as well. Feel free to ask questions in this thread.

Flatten List of List​


Python:
import itertools
l = [ [1, 2, 3], [4, 5, 6] ]
[i for i in itertools.chain.from_iterable(l)]
>>[1, 2, 3, 4, 5, 6]

Find Intersection of Lists​

Cast the list to a set and use the & bitwise operator.

Python:
>>> a = [1,2,3,4,5]
>>> b = [1,3,5,6]
>>> list(set(a) & set(b))
[1, 3, 5]

Group List of Dicts By Key​


Python:
from collections import defaultdict

def group_by_key(records, key):
    grouped = defaultdict(list)
    for record in records:
        grouped[record[key]].append(record)
    return grouped

records = [{"name": "Alice", "age": 25, "city": "New York"},
           {"name": "Bob", "age": 30, "city": "London"},
           {"name": "Charlie", "age": 25, "city": "New York"}]
grouped_by_city = group_by_key(records, "city")
print(grouped_by_city)
 

Nested Dictionary Wrapper​

Sometimes you have a dictionary with a nested dictionary inside of it.

JSON:
{
  "foo": "bar",
  "bin": {
    "baz": 1
  }
}

In Python you can use the .get() method or an index (with brackets) to retrieve an item, but this becomes cumbersome with nested dictionaries.

I use the following wrapper class to allow for quick attribute style lookups for objects like this.

Python:
from typing import Any


class NestedDictWrapper:
    def __init__(self, data: dict[Any, Any]):
        self._data = data

    def __getattr__(self, key: Any) -> Any:
        if not self._data.get(key):
            raise KeyError(f"{key} not found in root data")

        if isinstance(self._data[key], dict):
            return NestedDictWrapper(self._data[key])

        return self._data.get(key)

The magic exists in the __getattr__ method, if the value type is dict, simply return another instance of the NestedDictWrapper with the sub-dict.

This allows for the following code to function.

Code:
>>> data = {"foo": "bar","bin": {"baz": 1}}
>>> d = DictWrapper(data)
>>> d.foo
'bar'
>>> d.bin.baz
1
 

Two Decorator Patterns​


Basic Decorator​

I typically use this pattern as an entry point into batch job scripts.

Wrap your main function in this decorator and do any configuration needed in the decorator body.

Python:
def basic_job_setup(f: callable) -> callable:

    @wraps(f)
    def setup(*args, **kwargs):
        # Job Setup Code Here
        return f(*args, **kwargs)

    return setup

Decorator with Arguments​

Sometime you'll want to customize what a decorator does and pass arguments to it.

Python:
def parametarized_job_setup(x: str) -> callable:

    def inner_setup(f: callable) -> callable:
        @wraps(f)
        def setup(*args, **kwargs):
            # Job Setup Code Here
            # Probably do something with 'x'
            return f(*args, **kwargs)

        return setup

    return inner_setup
 
In the spirit of contributing something to this community, I've compiled a collection of code snippets to share. These are meant to be reference material for anyone interested, but there are also code snippets that I have used in real life at one point or another. Hoping others might contribute as well. Feel free to ask questions in this thread.

Flatten List of List​


Python:
import itertools
l = [ [1, 2, 3], [4, 5, 6] ]
[i for i in itertools.chain.from_iterable(l)]
>>[1, 2, 3, 4, 5, 6]

Find Intersection of Lists​

Cast the list to a set and use the & bitwise operator.

Python:
>>> a = [1,2,3,4,5]
>>> b = [1,3,5,6]
>>> list(set(a) & set(b))
[1, 3, 5]

Group List of Dicts By Key​


Python:
from collections import defaultdict

def group_by_key(records, key):
    grouped = defaultdict(list)
    for record in records:
        grouped[record[key]].append(record)
    return grouped

records = [{"name": "Alice", "age": 25, "city": "New York"},
           {"name": "Bob", "age": 30, "city": "London"},
           {"name": "Charlie", "age": 25, "city": "New York"}]
grouped_by_city = group_by_key(records, "city")
print(grouped_by_city)
Very interested in more you got to teach
 
In the spirit of contributing something to this community, I've compiled a collection of code snippets to share. These are meant to be reference material for anyone interested, but there are also code snippets that I have used in real life at one point or another. Hoping others might contribute as well. Feel free to ask questions in this thread.

Flatten List of List​


Python:
import itertools
l = [ [1, 2, 3], [4, 5, 6] ]
[i for i in itertools.chain.from_iterable(l)]
>>[1, 2, 3, 4, 5, 6]

Find Intersection of Lists​

Cast the list to a set and use the & bitwise operator.

Python:
>>> a = [1,2,3,4,5]
>>> b = [1,3,5,6]
>>> list(set(a) & set(b))
[1, 3, 5]

Group List of Dicts By Key​


Python:
from collections import defaultdict

def group_by_key(records, key):
    grouped = defaultdict(list)
    for record in records:
        grouped[record[key]].append(record)
    return grouped

records = [{"name": "Alice", "age": 25, "city": "New York"},
           {"name": "Bob", "age": 30, "city": "London"},
           {"name": "Charlie", "age": 25, "city": "New York"}]
grouped_by_city = group_by_key(records, "city")
print(grouped_by_city)
Very interested in more you got to teach
Good initiative ,will add later
Sound good can't wait fr fr I've been learning on my own. But I just learn better when touch by someone .
 

Group a list of datetime objects into groups of consecutive dates​


Python:
def group_consecutive_dates(dates: List[datetime]) -> List[List[datetime]]:
    dates.sort()
    result = []
    current_group = [dates[0]]
    for i in range(1, len(dates)):
        if dates[i] == dates[i - 1] + timedelta(days=1):
            current_group.append(dates[i])
        else:
            result.append(current_group)
            current_group = [dates[i]]
    result.append(current_group)
    return result

Input dates​

Code:
dates = [
    datetime(2022, 1, 1),
    datetime(2022, 1, 2),
    datetime(2022, 1, 5),
    datetime(2022, 1, 6),
    datetime(2022, 1, 7),
    datetime(2022, 1, 15),
    datetime(2022, 1, 16),
]

Output dates​

Code:
[[datetime.datetime(2022, 1, 1, 0, 0), datetime.datetime(2022, 1, 2, 0, 0)],
 [datetime.datetime(2022, 1, 5, 0, 0),
  datetime.datetime(2022, 1, 6, 0, 0),
  datetime.datetime(2022, 1, 7, 0, 0)],
 [datetime.datetime(2022, 1, 15, 0, 0), datetime.datetime(2022, 1, 16, 0, 0)]]
 
Back
Top