script_5.py - List Sorting and Custom Sort Keys
Code
See script_5.py for full code.
Explanation
Line 9-15: List of dictionaries
- Each dict represents a product
- Dict keys: "name", "price", "rating", "stock"
- products is list type containing dict elements
Line 21: by_price = sorted(products, key=lambda x: x["price"])
- sorted() is built-in function returning new sorted list
- Original list unchanged (non-mutating)
- key parameter specifies sort criteria
- lambda x: x["price"] is anonymous function
- Lambda takes dict x, returns price value
- Sorts by price in ascending order (default)
Line 27: by_rating = sorted(products, key=lambda x: x["rating"], reverse=True)
- reverse=True parameter sorts descending (high to low)
- Boolean parameter changes sort order
Line 33: by_availability = sorted(products, key=lambda x: (x["stock"] == 0, -x["rating"]))
- Lambda returns tuple for multi-level sorting
- First sorts by x["stock"] == 0 (boolean: False < True)
- Then sorts by -x["rating"] (negative for descending within group)
- Out-of-stock items come last, within each group sorted by rating
Line 41: case_insensitive = sorted(words, key=str.lower)
- str.lower is method reference (no parentheses)
- Applied to each string element
- Returns lowercase version for comparison
- Original strings unchanged