pydash: Functional Programming in Python Made Easy

Working with complex data structures and performing functional operations in Python often requires repetitive code, reducing readability and slowing development.

pydash solves this by offering utility functions that simplify operations on lists, dictionaries, and other data structures. This enables a more expressive and concise approach to data manipulation.

Working with Lists

pydash provides several useful functions for manipulating lists:

Flattening Nested Lists

Use flatten to flatten a single level of nesting:

from pydash import py_

nested_list = [[1, 2], [3, 4, 5]]
flattened = py_.flatten(nested_list)
print(flattened)  # [1, 2, 3, 4, 5]

For deeply nested lists, use flatten_deep:

deeply_nested = [[1, 2, [4, 5]], [6, 7]]
fully_flattened = py_.flatten_deep(deeply_nested)
print(fully_flattened)  # [1, 2, 4, 5, 6, 7]

Chunking Lists

Split a list into smaller groups using chunk:

numbers = [1, 2, 3, 4, 5]
chunked = py_.chunk(numbers, 2)
print(chunked)  # [[1, 2], [3, 4], [5]]

Working with Dictionaries

pydash offers convenient methods for dictionary manipulation:

Omitting Dictionary Attributes

Remove specific keys from a dictionary using omit:

fruits = {"name": "apple", "color": "red", "taste": "sweet"}
without_name = py_.omit(fruits, "name")
print(without_name)  # {'color': 'red', 'taste': 'sweet'}

Accessing Nested Dictionary Attributes

Use get to easily access nested dictionary values:

apple = {
    "price": {
        "in_season": {"store": {"Walmart": [2, 4], "Aldi": 1}},
        "out_of_season": {"store": {"Walmart": [3, 5], "Aldi": 2}},
    }
}

walmart_price = py_.get(apple, "price.in_season.store.Walmart[0]")
print(walmart_price)  # 2

Working with Lists of Dictionaries

pydash shines when working with lists of dictionaries:

Finding Item Index

Use find_index to locate items based on a condition:

fruits = [
    {"name": "apple", "price": 2},
    {"name": "orange", "price": 2},
    {"name": "grapes", "price": 4},
]

apple_index = py_.find_index(fruits, lambda fruit: fruit["name"] == "apple")
print(apple_index)  # 0

Filtering Objects

Filter objects based on matching attributes:

apples = py_.filter_(fruits, {"name": "apple"})
print(apples)  # [{'name': 'apple', 'price': 2}]

Mapping Nested Values

Extract nested values from a list of dictionaries:

nested_fruits = [
    {"apple": {"price": [0, 1], "color": "red"}},
    {"apple": {"price": [2, 3], "color": "green"}},
]

second_prices = py_.map_(nested_fruits, "apple.price[1]")
print(second_prices)  # [1, 3]

Function Utilities

pydash provides utilities for working with functions:

Executing Functions Multiple Times

Use times to run a function a specified number of times:

messages = py_.times(3, lambda i: f"Message {i}")
print(messages)  # ['Message 0', 'Message 1', 'Message 2']

Method Chaining

pydash allows you to chain multiple operations for more expressive code:

fruits = ["apple", "orange", "grapes"]

result = (
    py_.chain(fruits)
    .without("grapes")
    .reject(lambda fruit: fruit.startswith("a"))
    .value()
)

print(result)  # ['orange']

You can also use custom functions in chains:

def get_price(fruit):
    prices = {"apple": 2, "orange": 2, "grapes": 4}
    return prices[fruit]

total_price = py_.chain(fruits).map(get_price).sum().value()
print(total_price)  # 8

Link to pydash.

Related Posts

Related Posts

Scroll to Top

Work with Khuyen Tran

Work with Khuyen Tran