π§ 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
Top comments (0)