Dictionaries

A dictionary in Python is a collection that stores data in key-value pairs. Each key is unique, and it is used to access its corresponding value. Dictionaries are mutable, meaning you can change, add, or remove items after creating them.

Key Features of Dictionaries

  1. Key-Value Pairs: Data is stored as key: value.
  2. Unique Keys: Each key in a dictionary must be unique.
  3. Mutable: You can change, add, or delete items in a dictionary.
  4. Unordered (prior to Python 3.7): Dictionaries do not maintain the order of items before Python 3.7. From Python 3.7 onwards, dictionaries maintain insertion order.

Creating a Dictionary

You can create a dictionary using curly braces {} or the dict() function.

Examples:

Python
Copy
# Empty dictionary
empty_dict = {}

# Dictionary with data
person = {
    "name": "John",
    "age": 30,
    "city": "New York"
}

# Using the dict() function
employee = dict(id=101, role="developer")
print(employee)  # Output: {'id': 101, 'role': 'developer'}

Accessing Values

You can access values in a dictionary using their keys.

Examples:

Python
Copy
person = {"name": "Alice", "age": 25, "city": "London"}

# Accessing a value by its key
print(person["name"])  # Output: Alice

# Using get() method (avoids error if the key doesn't exist)
print(person.get("age"))  # Output: 25
print(person.get("country", "Not Found"))  # Output: Not Found

Adding or Updating Items

You can add new key-value pairs or update existing ones.

Examples:

Python
Copy
person = {"name": "Alice", "age": 25}

# Add a new key-value pair
person["city"] = "London"

# Update an existing value
person["age"] = 26

print(person)  # Output: {'name': 'Alice', 'age': 26, 'city': 'London'}

Removing Items

Dictionaries provide several methods to remove items.

Examples:

Python
Copy
person = {"name": "Alice", "age": 25, "city": "London"}

# Remove a specific key-value pair using del
del person["age"]

# Remove a key-value pair using pop()
city = person.pop("city")
print(city)  # Output: London

# Remove all items using clear()
person.clear()
print(person)  # Output: {}

Dictionary Methods

Method Description Example
get(key[, default]) Returns the value for a key, or default if not found person.get("name", "Unknown")
keys() Returns all keys in the dictionary person.keys()
values() Returns all values in the dictionary person.values()
items() Returns all key-value pairs as tuples person.items()
pop(key[, default]) Updates the dictionary with key-value pairs from another dictionary person.update(new_data)
clear() Removes all items from the dictionary person.clear()
copy() Returns a shallow copy of the dictionary new_dict = person.copy()

Looping Through a Dictionary

You can iterate through a dictionary to access keys, values, or both.

Examples:

Python
Copy
person = {"name": "Alice", "age": 25, "city": "London"}

# Loop through keys
for key in person:
    print(key)

# Loop through values
for value in person.values():
    print(value)

# Loop through key-value pairs
for key, value in person.items():
    print(f"{key}: {value}")

Dictionary Comprehensions

You can create a dictionary using a concise syntax called dictionary comprehension.

Examples:

Python
Copy
# Create a dictionary from a list
squares = {x: x**2 for x in range(1, 6)}
print(squares)  # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

# Filter dictionary during creation
even_squares = {x: x**2 for x in range(1, 6) if x % 2 == 0}
print(even_squares)  # Output: {2: 4, 4: 16}

Nested Dictionaries

A dictionary can contain other dictionaries as values.

Example:

Python
Copy
students = {
    "101": {"name": "Alice", "age": 20},
    "102": {"name": "Bob", "age": 22},
}

# Accessing nested dictionary
print(students["101"]["name"])  # Output: Alice

When to Use Dictionaries

  • When you need to store data with a relationship between a key and a value (e.g., student ID and name, product and price).
  • When you need fast lookups (dictionaries are optimized for key-based access).