Virtual assistance

Python Dictionaries

Dictionaries are mutable, unordered collections of key-value pairs. They provide fast lookups and are one of Python's most powerful data structures.

Python Dictionaries

What are Dictionaries?

Dictionaries are unordered collections of key-value pairs. Keys must be immutable (strings, numbers, tuples), while values can be any data type. They provide O(1) average time complexity for lookups.

"Dictionaries map keys to values, providing fast data retrieval."

Creating Dictionaries

# Empty dictionary
empty_dict = {}

# Dictionary with key-value pairs
person = {
    "name": "Alice",
    "age": 25,
    "city": "New York"
}

# Using dict() constructor
student = dict(name="Bob", age=20, grade="A")

# Mixed data types
mixed = {
    "string": "hello",
    "number": 42,
    "list": [1, 2, 3],
    "tuple": (4, 5),
    "dict": {"nested": "value"}
}

print(person["name"])  # Alice
print(student["grade"]) # A

Dictionary Operations

person = {"name": "Alice", "age": 25, "city": "New York"}

# Accessing values
print(person["name"])     # Alice
print(person.get("age"))  # 25
print(person.get("salary", "Not found"))  # Not found

# Adding/Updating values
person["email"] = "alice@example.com"
person["age"] = 26

# Removing items
del person["city"]
removed_value = person.pop("email")
last_item = person.popitem()  # Removes last inserted item

# Checking membership
print("name" in person)   # True
print("city" in person)   # False

# Length
print(len(person))        # 2

Dictionary Methods

Dictionaries provide many useful methods for data manipulation:

person = {"name": "Alice", "age": 25}
grades = {"math": 90, "science": 85, "english": 88}

# keys(), values(), items()
print(person.keys())    # dict_keys(['name', 'age'])
print(person.values())  # dict_values(['Alice', 25])
print(person.items())   # dict_items([('name', 'Alice'), ('age', 25)])

# update() - Merge dictionaries
person.update({"city": "Boston", "email": "alice@example.com"})
print(person)

# clear() - Remove all items
temp = {"a": 1, "b": 2}
temp.clear()
print(temp)  # {}

# copy() - Shallow copy
original = {"x": 1, "y": [1, 2, 3]}
copied = original.copy()
copied["x"] = 10
copied["y"].append(4)
print(original)  # {'x': 1, 'y': [1, 2, 3, 4]} - list is shared!

# setdefault() - Get value or set default
result = grades.setdefault("history", 80)
print(result)  # 80 (new key added)
print(grades.setdefault("math", 100))  # 90 (existing key)

Dictionary Comprehensions

# Basic comprehension
squares = {x: x**2 for x in range(1, 6)}
print(squares)  # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

# Conditional comprehension
even_squares = {x: x**2 for x in range(1, 11) if x % 2 == 0}
print(even_squares)  # {2: 4, 4: 16, 6: 36, 8: 64, 10: 100}

# Transforming existing dictionary
original = {"a": 1, "b": 2, "c": 3}
doubled = {k: v*2 for k, v in original.items()}
print(doubled)  # {'a': 2, 'b': 4, 'c': 6}

# Swapping keys and values
swapped = {v: k for k, v in original.items()}
print(swapped)  # {1: 'a', 2: 'b', 3: 'c'}

Nested Dictionaries

# Nested dictionary structure
company = {
    "departments": {
        "engineering": {
            "employees": ["Alice", "Bob", "Charlie"],
            "budget": 500000
        },
        "sales": {
            "employees": ["David", "Eve"],
            "budget": 300000
        }
    },
    "location": "New York"
}

# Accessing nested values
print(company["departments"]["engineering"]["employees"][0])  # Alice

# Adding to nested dictionary
company["departments"]["marketing"] = {
    "employees": ["Frank"],
    "budget": 200000
}

# Iterating through nested dictionary
for dept_name, dept_info in company["departments"].items():
    print(f"{dept_name}: {len(dept_info['employees'])} employees")

Dictionary Performance

Dictionaries are highly optimized in Python:

  • Lookup Time: O(1) average case for key access
  • Insertion: O(1) average case
  • Deletion: O(1) average case
  • Space Efficient: Uses hash table implementation
  • Memory Usage: Higher than lists but worth it for fast lookups

Common Use Cases

  • Configuration Settings: Storing application settings
  • Data Lookup Tables: Fast data retrieval by key
  • Caching: Storing computed results
  • Counting Frequencies: Using as counters
  • JSON-like Data: Representing structured data
  • Database Records: Storing row data

Dictionaries are one of Python's most powerful and frequently used data structures. Their fast lookup times and flexibility make them ideal for many programming tasks.