Useful and handy code snippets using dictionary

Here are some handy and practical Python code snippets using dictionaries, focusing on automation, data processing, and general-purpose tasks:


1. Dictionary for Dynamic Configuration

config = {
    "database": "my_database",
    "host": "localhost",
    "port": 5432,
    "user": "admin",
    "password": "password123"
}

# Use configuration
connection_string = "dbname={database} host={host} port={port} user={user} password={password}".format(**config)
print("Connection String:", connection_string)

2. Mapping Keys Dynamically

data = {"id": 1, "name": "John", "age": 30}
key_mapping = {"name": "full_name", "age": "years_old"}

mapped_data = {key_mapping.get(k, k): v for k, v in data.items()}
print("Mapped Data:", mapped_data)

3. Summing Values by Group

transactions = [
    {"category": "food", "amount": 50},
    {"category": "entertainment", "amount": 100},
    {"category": "food", "amount": 30},
    {"category": "utilities", "amount": 70},
]

category_totals = {}
for txn in transactions:
    category_totals[txn["category"]] = category_totals.get(txn["category"], 0) + txn["amount"]

print("Category Totals:", category_totals)

4. Nested Dictionary Creation

data = [
    {"region": "North", "state": "NY", "sales": 100},
    {"region": "North", "state": "NJ", "sales": 200},
    {"region": "South", "state": "FL", "sales": 150},
]

nested_dict = {}
for item in data:
    region = item["region"]
    state = item["state"]
    sales = item["sales"]
    nested_dict.setdefault(region, {})[state] = sales

print("Nested Dictionary:", nested_dict)

5. Counting Occurrences Using a Dictionary

words = ["apple", "banana", "apple", "orange", "banana", "apple"]

word_count = {}
for word in words:
    word_count[word] = word_count.get(word, 0) + 1

print("Word Count:", word_count)

6. Updating Dictionary Based on Conditions

employees = {
    "John": {"department": "HR", "salary": 50000},
    "Alice": {"department": "IT", "salary": 60000},
}

# Increase salary for IT employees
for name, info in employees.items():
    if info["department"] == "IT":
        info["salary"] += 5000

print("Updated Employees:", employees)

7. Merging Two Dictionaries

dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}

merged_dict = {**dict1, **dict2}  # Overwrites `b` with 3
print("Merged Dictionary:", merged_dict)

8. Reverse Dictionary Lookup

lookup = {"a": 1, "b": 2, "c": 3}
reversed_lookup = {v: k for k, v in lookup.items()}
print("Reversed Lookup:", reversed_lookup)

9. Flattening a Nested Dictionary

pythonCopy codenested_dict = {"a": {"b": {"c": 1}, "d": 2}, "e": 3}

def flatten_dict(d, parent_key="", sep="."):
    items = []
    for k, v in d.items():
        new_key = f"{parent_key}{sep}{k}" if parent_key else k
        if isinstance(v, dict):
            items.extend(flatten_dict(v, new_key, sep=sep).items())
        else:
            items.append((new_key, v))
    return dict(items)

flat_dict = flatten_dict(nested_dict)
print("Flattened Dictionary:", flat_dict)

10. Using a Dictionary for Function Dispatch

pythonCopy codedef add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    return a / b if b != 0 else "Division by zero"

operations = {
    "add": add,
    "subtract": subtract,
    "multiply": multiply,
    "divide": divide
}

operation = "multiply"
result = operations[operation](10, 5)
print(f"Result of {operation}:", result)

11. Grouping Items Using a Dictionary

students = [
    {"name": "Alice", "grade": "A"},
    {"name": "Bob", "grade": "B"},
    {"name": "Charlie", "grade": "A"},
    {"name": "David", "grade": "C"},
]

grouped = {}
for student in students:
    grouped.setdefault(student["grade"], []).append(student["name"])

print("Grouped Students:", grouped)

12. Dictionary for Dynamic Query Building

filters = {"status": "active", "category": "IT"}

query = "SELECT * FROM employees WHERE " + " AND ".join(f"{k} = '{v}'" for k, v in filters.items())
print("Generated Query:", query)

13. Dictionary for Default Values

from collections import defaultdict

default_dict = defaultdict(int)
default_dict["a"] += 1
default_dict["b"] += 2
print("Default Dictionary:", dict(default_dict))

14.Dynamic DataFrame Transformations

Apply transformations dynamically based on conditions:

transformations = {
    "uppercase": lambda col: F.upper(F.col(col)),
    "add_prefix": lambda col: F.concat(F.lit("prefix_"), F.col(col)),
}

transformation = "uppercase"
column = "name"

df = df.withColumn(column, transformations[transformation](column))
df.show()

Discover more from HintsToday

Subscribe to get the latest posts sent to your email.

Pages ( 3 of 4 ): « Previous12 3 4Next »

Discover more from HintsToday

Subscribe now to keep reading and get access to the full archive.

Continue reading