Dictionaries

Dictionaries are one of the most important and versatile data structures in Python. They store data in key-value pairs, allowing for fast access and efficient modification.

This tutorial will cover the basics of dictionaries, show you how to use them, and explain how to iterate through them.

## Basics of Dictionaries

Dictionaries are defined using curly braces `{}` and allow for the storage of key-value pairs. Unlike lists, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type (like strings, numbers, or tuples).

### Creating a Dictionary

You can create a dictionary in several ways.

# Creating an empty dictionary
dict1 = {}

# Creating a dictionary with initial key-value pairs
dict2 = {
    "name": "Alice",
    "age": 25,
    "city": "New York"
}

# Using the dict() constructor
dict3 = dict(name="Bob", age=30, city="Los Angeles")

print(dict1)
print(dict2)
print(dict3)
{}
{'name': 'Alice', 'age': 25, 'city': 'New York'}
{'name': 'Bob', 'age': 30, 'city': 'Los Angeles'}
**Explanation:**

- `dict1` is initialized as an empty dictionary.
- `dict2` and `dict3` are initialized with key-value pairs.

### Accessing Values

You can access values in a dictionary using their keys.

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

print(person["name"])
print(person.get("age"))

# Accessing a non-existing key using get()
print(person.get("address", "Address not found"))
Alice
25
Address not found
**Explanation:**

- `person["name"]`: Accesses the value associated with the key `"name"`.
- `person.get("age")`: Another way to access the value, which is useful if the key might not exist.
- `person.get("address", "Address not found")`: Returns "Address not found" instead of raising an error if the key doesn't exist.

### Modifying Values

You can modify the values in a dictionary by accessing the keys directly.

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

# Modifying existing key
person["age"] = 26

# Adding a new key-value pair
person["email"] = "[email protected]"

print(person)
{'name': 'Alice', 'age': 26, 'city': 'New York', 'email': '[email protected]'}
**Explanation:**

- `person["age"] = 26`: Updates the value of the existing key `"age"`.
- `person["email"] = "[email protected]"`: Adds a new key-value pair to the dictionary.

### Removing Key-Value Pairs

You can remove key-value pairs from a dictionary using the `del` statement or the `pop` method.

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

# Removing a key-value pair using del
del person["city"]

# Removing a key-value pair using pop()
email = person.pop("email", "Email not found")

print(person)
print("Email:", email)
{'name': 'Alice', 'age': 25}
Email: Email not found
**Explanation:**

- `del person["city"]`: Removes the key-value pair with key `"city"`.
- `person.pop("email", "Email not found")`: Removes and returns the value for the key `"email"`. If the key doesn't exist, it returns "Email not found".

## Iterating Through a Dictionary

There are several ways to iterate through dictionaries to access keys, values, or key-value pairs.

### Iterating Through Keys

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

for key in person:
    print(key)
name
age
city
**Explanation:**

- This loops through each key in the dictionary `person`.

### Iterating Through Values

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

for value in person.values():
    print(value)
Alice
25
New York
**Explanation:**

- This loops through each value in the dictionary `person` using the `.values()` method.

### Iterating Through Key-Value Pairs

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

for key, value in person.items():
    print(f"Key: {key}, Value: {value}")
Key: name, Value: Alice
Key: age, Value: 25
Key: city, Value: New York
**Explanation:**

- This loops through each key-value pair in the dictionary `person` using the `.items()` method.

### Checking for the Existence of Keys

You can check if a key exists in the dictionary using the `in` keyword.

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

# Check if key exists
if "name" in person:
    print("Name exists in the dictionary.")
else:
    print("Name does not exist in the dictionary.")
Name exists in the dictionary.
**Explanation:**

- `if "name" in person`: Checks whether the key `"name"` exists in the dictionary `person`.