Python Dictionary & Function: Advanced Usage Patterns

  1. Dictionary Fundamentals and Efficient Manipulation

A dict in Python is a mutable, unordered collection of key-value pairs, where keys must be hashable (e.g., strings, numbers, tuples) and unique.

Creation is straightforward using curly braces or the dict() constructor:

info = {'identity': 'Student', 'level': 3}
profile = dict(name='Nguyen', score=92)

Values may be of any type—including nested collections—and retrieval, modification, or removal are all performed by key:

# Access
print(info['level'])           # 3

# Update or add
info['level'] = 4              # Update existing
info['department'] = 'CS'      # Add new key

# Delete
del info['identity']           # Raise KeyError if key absent
removed = info.pop('level')    # Safe retrieval & deletion

To handle missing keys gracefully, use get() with optional defaults:

age = profile.get('age', 18)   # Returns 18 if 'age' not found
  1. Dictionary Traversal Strategies

Python offers multiple ways to iterate over dictionaries, each suited to specific needs:

# Iterate only keys (implicit)
for key in profile:
    print(key, profile[key])

# Explicit key iteration
for key in profile.keys():
    print(key)

# Iterate only values
for val in profile.values():
    print(val)

# Iterate key-value pairs as tuples
for k, v in profile.items():
    print(f'{k}: {v}')

Dictionary comprehensions provide a concise way to construct or transform mappings:

scores = {'Alice': 85, 'Bob': 90, 'Cathy': 78}
passes = {name: grade for name, grade in scores.items() if grade >= 80}
# {'Alice': 85, 'Bob': 90}
  1. Function Definitions & Invocations

A function encapsulates logic for reuse. Define it using def, and invoke by name with matching arguments:

def compute_stats(values):
    total = sum(values)
    avg = total / len(values) if values else 0
    return {'sum': total, 'average': avg}

result = compute_stats([10, 20, 30])
# {'sum': 60, 'average': 20.0}

Python functions support multiple argument styles, enabling flexible call signatures:

Positional vs keyword arguments

def configure(mode='debug', timeout=30, retries=3):
    print(f'Mode: {mode}, Timeout: {timeout}s, Retries: {retries}')

configure()                     # All defaults
configure('production')         # Positional override
configure(timeout=60, mode='test')  # Keyword, order-independent
configure(30, retries=5)        # Mixed positional & keyword

Variable-length argument lists

Use *args and **kwargs to accept any number of arguments:

def log_events(event_type, *details, **metadata):
    print(f'Event: {event_type}')
    for item in details:
        print(f'- {item}')
    for key, value in metadata.items():
        print(f'{key}: {value}')

log_events('Login', 'User123', 'IP:192.168.1.1', timestamp='2025-04-05', region='APAC')
  1. Advanced Dictionary Manipulations

Merging & updating dictionaries

base_config = {'host': 'localhost', 'port': 8080}
env_config = {'port': 8000, 'debug': True}

# Python 3.9+ merge (non-destructive)
full_config = base_config | env_config         # {'host': 'localhost', 'port': 8000, 'debug': True}

# In-place update (destructive to base_config)
base_config.update(env_config)

Default-initialized dictionaries

collections.defaultdict eliminates manual key-existence checks:

from collections import defaultdict

groups = defaultdict(list)
students = [('A', 'Group1'), ('B', 'Group1'), ('C', 'Group2')]

for name, group in students:
    groups[group].append(name)

# defaultdict(<class 'list'>, {'Group1': ['A', 'B'], 'Group2': ['C']})

Counting elements

Use collections.Counter for frequency mapping:

from collections import Counter

data = ['x', 'y', 'x', 'z', 'y', 'x']
freq = Counter(data)
# Counter({'x': 3, 'y': 2, 'z': 1})

print(freq.most_common(2))  # [('x', 3), ('y', 2)]
  1. Higher-order Patterns with Functions

Functions in Python are first-class citizens, enabling powerful constructs:

Function as return values

def make_multiplier(factor):
    def multiply(n):
        return n * factor
    return multiply

times_three = make_multiplier(3)
print(times_three(7))  # 21

Function as arguments ( callbacks / strategies )

def transform(items, operation):
    return [operation(item) for item in items]

nums = [2, 4, 6]
squared = transform(nums, lambda x: x**2)
# [4, 16, 36]

Partial application with functools

from functools import partial

def power(base, exp):
    return base ** exp

square = partial(power, exp=2)
cube = partial(power, exp=3)

print(square(5))  # 25
print(cube(2))    # 8

Thẻ: dictionary comprehension Lambda Collections defaultdict

Đăng vào ngày 8 tháng 6 lúc 21:43