> ## Documentation Index
> Fetch the complete documentation index at: https://rajanand.org/llms.txt
> Use this file to discover all available pages before exploring further.

# Python Dictionaries

## 1. **What is a Dictionary?**

* A **dictionary** is a collection of key-value pairs that are unordered, mutable (changeable), and indexed by keys.
* Keys must be unique and immutable (e.g., strings, numbers, tuples), while values can be of any type.
* Dictionaries are defined using curly braces `{}` or the `dict()` constructor.

**Example**:

```python theme={"system"}
person = {"name": "Raj", "age": 25, "city": "Chennai"}
```

## 2. **Dictionary Operations**

### **1. Accessing Values**

* Use the key to access the corresponding value.
* If the key does not exist, it raises a `KeyError`. Use the `get()` method to avoid this.

**Examples**:

```python theme={"system"}
person = {"name": "Ram", "age": 30, "city": "Bangalore"}
print(person["name"])  # Output: Ram
print(person.get("age"))  # Output: 30
print(person.get("country", "India"))  # Output: India (default value if key doesn't exist)
```

### **2. Adding/Updating Elements**

* Add a new key-value pair or update an existing one using the assignment operator `=`.

**Example**:

```python theme={"system"}
person = {"name": "Anand", "age": 28}
person["city"] = "Mumbai"  # Add new key-value pair
person["age"] = 29  # Update existing key
print(person)  # Output: {'name': 'Anand', 'age': 29, 'city': 'Mumbai'}
```

### **3. Removing Elements**

* Use `pop()` to remove a key-value pair by key (returns the value).
* Use `popitem()` to remove the last inserted key-value pair (Python 3.7+).
* Use `del` to delete a key-value pair.
* Use `clear()` to remove all key-value pairs.

**Examples**:

```python theme={"system"}
person = {"name": "Bala", "age": 35, "city": "Delhi"}
age = person.pop("age")  # Remove 'age' key
print(age)  # Output: 35
print(person)  # Output: {'name': 'Bala', 'city': 'Delhi'}

person.popitem()  # Remove last inserted key-value pair
print(person)  # Output: {'name': 'Bala'}

del person["name"]  # Delete 'name' key
print(person)  # Output: {}

person.clear()  # Remove all key-value pairs
print(person)  # Output: {}
```

### **4. Checking for Keys**

* Use the `in` keyword to check if a key exists in the dictionary.

**Example**:

```python theme={"system"}
person = {"name": "Karthik", "age": 40}
print("name" in person)  # Output: True
print("city" in person)  # Output: False
```

### **5. Iterating Over a Dictionary**

* Use loops to iterate over keys, values, or key-value pairs.

**Examples**:

```python theme={"system"}
person = {"name": "Kumar", "age": 45, "city": "Hyderabad"}

# Iterate over keys
for key in person:
    print(key)  # Output: name, age, city

# Iterate over values
for value in person.values():
    print(value)  # Output: Kumar, 45, Hyderabad

# Iterate over key-value pairs
for key, value in person.items():
    print(f"{key}: {value}")
# Output:
# name: Kumar
# age: 45
# city: Hyderabad
```

### **6. Length**

* Use `len()` to find the number of key-value pairs in a dictionary.

**Example**:

```python theme={"system"}
person = {"name": "David", "age": 50}
print(len(person))  # Output: 2
```

## 3. **Dictionary Methods**

### **1. `keys()`**

* Returns a view of all keys in the dictionary.

**Example**:

```python theme={"system"}
person = {"name": "Kannan", "age": 55}
print(person.keys())  # Output: dict_keys(['name', 'age'])
```

### **2. `values()`**

* Returns a view of all values in the dictionary.

**Example**:

```python theme={"system"}
person = {"name": "Siva", "age": 60}
print(person.values())  # Output: dict_values(['Siva', 60])
```

### **3. `items()`**

* Returns a view of all key-value pairs as tuples.

**Example**:

```python theme={"system"}
person = {"name": "Ramesh", "age": 65}
print(person.items())  # Output: dict_items([('name', 'Ramesh'), ('age', 65)])
```

### **4. `update()`**

* Merges another dictionary into the current one (updates existing keys and adds new ones).

**Example**:

```python theme={"system"}
person = {"name": "Suresh", "age": 70}
person.update({"city": "Pune", "age": 71})
print(person)  # Output: {'name': 'Suresh', 'age': 71, 'city': 'Pune'}
```

### **5. `copy()`**

* Returns a shallow copy of the dictionary.

**Example**:

```python theme={"system"}
person = {"name": "Sathish", "age": 75}
person_copy = person.copy()
print(person_copy)  # Output: {'name': 'Sathish', 'age': 75}
```

## 4. **Dictionary Comprehensions**

* A concise way to create dictionaries using a single line of code.
* Syntax: `{key: value for item in iterable}`

**Example**:

```python theme={"system"}
squares = {x: x ** 2 for x in range(5)}
print(squares)  # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
```

## 5. **Nested Dictionaries**

* A dictionary can contain other dictionaries, creating a multi-level structure.

**Example**:

```python theme={"system"}
people = {
    "Raj": {"age": 25, "city": "Chennai"},
    "Ram": {"age": 30, "city": "Bangalore"}
}
print(people["Raj"]["city"])  # Output: Chennai
```

## 6. **Additional Examples**

* **Creating a Dictionary**:
  ```python theme={"system"}
  person = {"name": "Sujatha", "age": 28, "city": "Coimbatore"}
  print(person)  # Output: {'name': 'Sujatha', 'age': 28, 'city': 'Coimbatore'}
  ```

* **Adding/Updating Elements**:
  ```python theme={"system"}
  person["occupation"] = "Engineer"
  print(person)  # Output: {'name': 'Sujatha', 'age': 28, 'city': 'Coimbatore', 'occupation': 'Engineer'}
  ```

* **Removing Elements**:
  ```python theme={"system"}
  person.pop("age")
  print(person)  # Output: {'name': 'Sujatha', 'city': 'Coimbatore', 'occupation': 'Engineer'}
  ```

* **Iterating Over a Dictionary**:
  ```python theme={"system"}
  for key, value in person.items():
      print(f"{key}: {value}")
  # Output:
  # name: Sujatha
  # city: Coimbatore
  # occupation: Engineer
  ```

* **Dictionary Comprehension**:
  ```python theme={"system"}
  names = ["Kavitha", "Sathish", "Suresh"]
  name_lengths = {name: len(name) for name in names}
  print(name_lengths)  # Output: {'Kavitha': 7, 'Sathish': 7, 'Suresh': 6}
  ```

## 7. **Best Practices**

* Use meaningful keys to make dictionaries easy to understand.
* Use `get()` to avoid `KeyError` when accessing keys that may not exist.
* Use dictionary comprehensions for concise and readable code.
