🧠 Python Basics: dict, list, f-string, and join()


✅ 1. Dictionary (dict) – key-value store

A dictionary stores data as key: value pairs. Think of it like a real-life dictionary, where a word (key) maps to its definition (value).

📌 Example:

person = {
    "name": "Alice",
    "age": 30,
    "job": "Nurse"
}

🔍 Accessing values:

print(person["name"])  # Output: Alice
print(person["age"])   # Output: 30

🛠️ Modifying:

person["age"] = 31

➕ Adding new key:

person["department"] = "Emergency"

✅ 2. List (list) – ordered collection of items

A list is a collection of values in a specific order.

📌 Example:

roles = ["cna", "nurse", "charge_nurse"]

🔍 Accessing:

print(roles[0])  # Output: cna

➕ Adding to a list:

roles.append("doctor")  # Now list has 4 items

✅ 3. f-string (formatted string) – for easy variable substitution in strings

An f-string is a string with an f at the beginning that allows you to put variables directly inside {}.

📌 Example:

name = "Alice"
print(f"Hello, {name}!")  # Output: Hello, Alice!

💡 Used in errors or logs:

valid_roles = ["cna", "nurse", "charge_nurse"]
print(f"Invalid role. Must be one of: {', '.join(valid_roles)}")

✅ 4. .join() – joins a list into a single string

You’ve already seen it above, but here’s a simpler view:

📌 Example:

fruits = ["apple", "banana", "cherry"]
result = " | ".join(fruits)
print(result)  # Output: apple | banana | cherry

You can use any string as the separator: ", ", " | ", " - ", etc.


🧩 All Together Example

user = {
    "name": "John",
    "email": "john@example.com",
    "roles": ["cna", "nurse"]
}

print(f"{user['name']} has roles: {', '.join(user['roles'])}")

Output:

John has roles: cna, nurse