Dunston
Registered Member
- Mar 4, 2023
- 64
- 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)