DEV Community

Muhammad Atif Iqbal
Muhammad Atif Iqbal

Posted on

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

🧠 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"
}
Enter fullscreen mode Exit fullscreen mode

πŸ” Accessing values:

print(person["name"])  # Output: Alice
print(person["age"])   # Output: 30
Enter fullscreen mode Exit fullscreen mode

πŸ› οΈ Modifying:

person["age"] = 31
Enter fullscreen mode Exit fullscreen mode

βž• Adding new key:

person["department"] = "Emergency"
Enter fullscreen mode Exit fullscreen mode

βœ… 2. List (list) – ordered collection of items

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

πŸ“Œ Example:

roles = ["cna", "nurse", "charge_nurse"]
Enter fullscreen mode Exit fullscreen mode

πŸ” Accessing:

print(roles[0])  # Output: cna
Enter fullscreen mode Exit fullscreen mode

βž• Adding to a list:

roles.append("doctor")  # Now list has 4 items
Enter fullscreen mode Exit fullscreen mode

βœ… 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!
Enter fullscreen mode Exit fullscreen mode

πŸ’‘ Used in errors or logs:

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

βœ… 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
Enter fullscreen mode Exit fullscreen mode

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'])}")
Enter fullscreen mode Exit fullscreen mode

Output:

John has roles: cna, nurse
Enter fullscreen mode Exit fullscreen mode

Top comments (0)