Python Dictionary

A Python dictionary is an unordered collection of items that stores data in key-value pairs. Dictionaries are mutable, allowing for dynamic addition and modification of key-value pairs.

Key Features of Dictionaries:

1. Unordered: The items in a dictionary do not maintain any specific order.

2. Mutable: You can change, add, or remove items after the dictionary is created.

3. Key-Value Pairs: Each item is stored as a pair, where a key maps to a corresponding value.

4. Unique Keys: Keys must be unique within a dictionary, but values can be duplicated.

Example of a Python Dictionary: Let's say we have a dictionary representing a fruit with its color and price:
fruit_info = {
    "apple": {"color": "red", "price": 0.5},
    "banana": {"color": "yellow", "price": 0.3},
    "cherry": {"color": "red", "price": 1.2}
}

Diagram Representation: Here's a simple representation of the dictionary:
+----------+---------------------+
|  Key     |        Value        |
+----------+---------------------+
| "apple"  | {"color": "red",   |
|          |  "price": 0.5}     |
+----------+---------------------+
| "banana" | {"color": "yellow", |
|          |  "price": 0.3}     |
+----------+---------------------+
| "cherry" | {"color": "red",   |
|          |  "price": 1.2}     |
+----------+---------------------+

Breakdown of the Diagram: - Keys: The left column represents the keys (e.g., `"apple"`, `"banana"`, `"cherry"`).

- Values: The right column represents the values, which can be complex data types (in this case, another dictionary containing color and price).

Step 1: Creating a Dictionary

A dictionary is created by enclosing key-value pairs in curly braces `{}`.
# Basic dictionary
student = {
    "name": "Alice",
    "age": 21,
    "grade": "A"
}
print("Student Dictionary:", student)

Output:

Student Dictionary: {'name': 'Alice', 'age': 21, 'grade': 'A'}
Explanation:
- Curly Braces `{}`: Define a dictionary, with each key-value pair separated by a comma.
- Key-Value Pairs: Each key is unique and is paired with a corresponding value.

Step 2: Accessing Values in a Dictionary

Values can be accessed using the key in square brackets `[]`.
# Accessing dictionary values
print("Name:", student["name"])
print("Age:", student["age"])

Output:

Name: Alice
Age: 21
Explanation:
- Square Brackets `[]`: Used to access the value associated with a given key.

Step 3: Adding or Updating Key-Value Pairs

Dictionaries are mutable, so new key-value pairs can be added, and existing ones can be updated.
# Adding or updating key-value pairs
student["age"] = 22  # Update
student["major"] = "Computer Science"  # Add
print("Updated Dictionary:", student)

Output:

Updated Dictionary: {'name': 'Alice', 'age': 22, 'grade': 'A', 'major': 'Computer Science'}
Explanation:
- Updating: Changing the value for an existing key.
- Adding: Creating a new key-value pair by assigning to a non-existing key.

Step 4: Removing Key-Value Pairs

You can remove items from a dictionary using `pop()`, `del`, or `popitem()`.
# Removing elements
student.pop("grade")  # Removes 'grade' key
del student["major"]  # Removes 'major' key
print("After Removal:", student)

Output:

After Removal: {'name': 'Alice', 'age': 22}
Explanation:
- `pop(key)`: Removes and returns the value of the specified key.
- `del`: Deletes the specified key-value pair directly.

Step 5: Dictionary Methods

Python dictionaries come with a set of useful methods like `keys()`, `values()`, and `items()`.
# Dictionary methods
print("Keys:", student.keys())
print("Values:", student.values())
print("Items:", student.items())

Output:

Keys: dict_keys(['name', 'age'])
Values: dict_values(['Alice', 22])
Items: dict_items([('name', 'Alice'), ('age', 22)])
Explanation:
- `keys()`: Returns all keys.
- `values()`: Returns all values.
- `items()`: Returns all key-value pairs as tuples.

Step 6: Using `get()` Method for Safe Access

The `get()` method allows you to access a key’s value, with an option for a default if the key is missing.
# Using get method
print("Grade:", student.get("grade", "N/A"))  # Returns 'N/A' if 'grade' is missing

Output:

Grade: N/A
Explanation:
- `get()`: Returns the value if the key exists; otherwise, it returns the default value provided.

Step 7: Dictionary Comprehension

Dictionary comprehension allows for concise creation and manipulation of dictionaries.
# Dictionary comprehension
squares = {x: x*x for x in range(1, 6)}
print("Squares Dictionary:", squares)

Output:

Squares Dictionary: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Explanation:
- Dictionary Comprehension: Creates dictionaries in a compact form with `{key: value for ...}` syntax.

Step 8: Merging Dictionaries

You can merge dictionaries using the `update()` method or with `**` unpacking.
# Merging dictionaries
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
merged = {**dict1, **dict2}  # Merges dict2 into dict1
print("Merged Dictionary:", merged)

Output:

Merged Dictionary: {'a': 1, 'b': 3, 'c': 4}
Explanation:
- `update()`: Updates a dictionary in place.
- `**` Unpacking: Merges dictionaries, with later values overwriting earlier ones for duplicate keys.

Step 9: Nested Dictionaries

Dictionaries can contain other dictionaries as values, creating nested structures.
# Nested dictionary
students = {
    "Alice": {"age": 21, "major": "Physics"},
    "Bob": {"age": 22, "major": "Chemistry"}
}
print("Nested Dictionary:", students)

Output:

Nested Dictionary: {'Alice': {'age': 21, 'major': 'Physics'}, 'Bob': {'age': 22, 'major': 'Chemistry'}}
Explanation:
- Nested Dictionary: Allows representation of complex hierarchical data within dictionaries.

Step 10: Looping Through a Dictionary

You can loop through dictionaries to access keys, values, or key-value pairs.
# Looping through a dictionary
for name, details in students.items():
    print(f"Name: {name}, Age: {details['age']}, Major: {details['major']}")

Output:

Name: Alice, Age: 21, Major: Physics
Name: Bob, Age: 22, Major: Chemistry
Explanation:
- `for key, value in dict.items()`: Efficiently loops through key-value pairs, ideal for nested dictionaries.

Step 11: Dictionary `defaultdict` from `collections`

Using `defaultdict` provides default values for keys, which is especially useful for handling missing keys.
from collections import defaultdict

# defaultdict with int as default type
count = defaultdict(int)
count['apple'] += 1  # Initializes 'apple' with 0 and then increments
print("Count dictionary:", dict(count))

Output:

Count dictionary: {'apple': 1}
Explanation:
- `defaultdict(int)`: Initializes keys with default `int` value (0) when accessed for the first time.

Step 12: Frozen Dictionaries with `MappingProxyType`

The `types.MappingProxyType` in the `types` module provides an immutable view of a dictionary.
from types import MappingProxyType

# Creating a read-only dictionary
read_only_dict = MappingProxyType(student)
print("Read-Only Dictionary:", read_only_dict)
# read_only_dict["name"] = "Bob"  # This line would raise a TypeError if uncommented

Output:

Read-Only Dictionary: {'name': 'Alice', 'age': 22}
Explanation:
- MappingProxyType: Creates an immutable dictionary that raises an error if modification is attempted.

Conclusion
Dictionaries are a versatile and powerful data structure in Python, ideal for storing and retrieving data based on unique keys. They are widely used for various applications, including configuration settings, JSON data manipulation, and more!

Previous: Python Tuple | Next: Python Set

<
>