🗓️ Day 19: Python Dictionary Use Cases

Dictionaries are one of Python's most powerful and versatile data structures. Their key-value pair system allows for flexible and efficient solutions to many common programming problems. Let's explore some key use cases.


1. Representing Structured Data (like JSON)

Dictionaries are perfect for modeling real-world objects or structured data, much like JSON objects in web development.

Example: User Profile

# A dictionary representing a user's profile
user_profile = {
    "user_id": 101,
    "username": "alex_coder",
    "email": "alex@example.com",
    "is_active": True,
    "permissions": ["read", "write"]
}

print(f"Username: {user_profile['username']}")
print(f"Permissions: {user_profile['permissions'][0]}")

2. Frequency Counting 📊

A classic use case for dictionaries is to count the occurrences of items in a sequence.

Example: Counting Characters in a String

text = "hello world"
char_counts = {}

for char in text:
    char_counts[char] = char_counts.get(char, 0) + 1

print(char_counts)

Pro Tip: Use collections.Counter for concise solutions:

from collections import Counter

text = "hello world"
print(Counter(text))

3. Caching / Memoization ⚡

Dictionaries can act as a cache to store the results of expensive computations (memoization).

Example: Fibonacci Sequence

fib_cache = {}

def fibonacci(n):
    if n in fib_cache:
        return fib_cache[n]
    if n <= 1:
        return n
    result = fibonacci(n - 1) + fibonacci(n - 2)
    fib_cache[n] = result
    return result

print(f"Fibonacci(35) = {fibonacci(35)}")

4. Grouping Data 📂

You can group items from a list based on a property using dictionaries.

Example: Grouping Students by Grade

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

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

print(grades)

🎤 Interview Questions and Answers

Q1: How do you merge two dictionaries?

Answer: Use either update() or dictionary unpacking (**).

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

merged1 = dict1.copy()
merged1.update(dict2)

merged2 = {**dict1, **dict2}

Q2: Difference between d[key] and d.get(key)?

d = {'a': 100}
print(d['a'])      # 100
print(d.get('b'))  # None
print(d.get('b', 0))# 0

Q3: Find key with maximum value?

scores = {'math': 95, 'science': 98, 'history': 88}
top_subject = max(scores, key=scores.get)
print(top_subject) # science