Python Practice Set (Part 5): Data Puzzles & Practical Manipulation
- Anubhav Somani
- Sep 2
- 2 min read

Python Data Puzzles: From List Comprehensions to Nested Data
Welcome to the fifth installment of our Python practice series! Now that you're comfortable with the basics, it's time to tackle challenges that reflect the kind of data manipulation you'll perform in real-world projects. In this set, we'll explore powerful techniques like list comprehensions, merging dictionaries, handling nested data structures, and writing robust code that can handle errors. Let's start solving!
1. Formatting an Invoice Line (Advanced String Formatting)
You have three pieces of data for an invoice line: an item name item = "widget", a quantity quantity = 15, and a price price = 2.50. Your task is to format this into a single string, formatted_line, that looks like this: ITEM: WIDGET | QTY: 015 | PRICE: $2.50.
The item name should be uppercase.
The item name section should be padded to 20 characters.
The quantity should be "zero-padded" to 3 digits (e.g., 5 becomes 005).
2. Squaring Numbers with a List Comprehension (Lists)
You are given a list of integers: numbers = [1, 2, 3, 4, 5, 6]. Create a new list called squared_evens that contains the squares of only the even numbers from the original list. Solve this using a single line of code with a list comprehension.
3. Combining User Profiles (Dictionary Merging)
You have two dictionaries containing different pieces of information about the same user. profile_part1 = {'username': 'tech_guru', 'email': 'guru@example.com'} profile_part2 = {'last_login': '2023-10-27', 'is_premium': True}
Combine these two dictionaries into a single dictionary called full_profile. Print the final, merged dictionary.
4. Accessing Nested Data (List of Dictionaries)
You have received data from an API as a list of dictionaries, where each dictionary represents a user. users_data = [ {'id': 101, 'name': 'Alice', 'role': 'editor'}, {'id': 102, 'name': 'Bob', 'role': 'viewer'}, {'id': 103, 'name': 'Charlie', 'role': 'admin'} ]
Your task is to find and print the name of the user whose role is "admin". You'll need to loop through the list and inspect each dictionary.
5. Safe Number Conversion (Error Handling & Type Casting)
You have a list of strings that represent potential numbers: raw_data = ["101", "250", "30.5", "invalid", "99", "N/A"]. Write a loop that iterates through this list and tries to convert each item into an integer. Create a new list called valid_numbers that contains only the successfully converted integers. Your code should not crash when it encounters a string that cannot be converted.
Hint: Use a try-except block to handle potential ValueError exceptions.
Comments