Dictionary

In python, a dictionary is a data structure that allows you to store and retrieve data using a key-value pair system. It's like a real-world dictionary where you look up a word (the key) to find its definition (the value).

Here's the most important concepts:

  1. Key-Value Pairs: A dictionary is a collection of key-value pairs, where each key is a unique identifier for a piece of data, and each value is the associated data itself.
  2. Unordered: Unlike lists, dictionaries are not ordered. This means that the elements in a dictionary don't have a specific order or position.
  3. Mutable: Dictionaries can be modified after creation, so you can add, change, or remove key-value pairs as needed.
  4. Unique Keys: Keys in a dictionary must be unique, meaning you can't have two identical keys with different values.

Here's a simple example of a Python dictionary:

🐍 Python Script
# Creating a dictionary
student = {
    "name": "Alice",
    "age": 25,
    "grade": "A"
}

# Accessing values using keys
print(student["name"])  # Output: "Alice"

# Modifying values
student["age"] = 26

# Adding a new key-value pair
student["city"] = "New York"

# Removing a key-value pair
del student["grade"]

# Checking if a key exists
if "city" in student:
    print("City:", student["city"])

In this example, we create a dictionary called student with three key-value pairs, access values using keys, modify values, add a new key-value pair, remove a key-value pair, and check if a key exists.

Dictionaries are versatile and useful for a wide range of tasks.