📖 Scenario: You work in a small bakery. You have a list of daily sales data for different types of bread. You want to save this data into a CSV file so you can share it with your manager easily.
🎯 Goal: Create a Python program that stores the bakery sales data in a dictionary, then export this data to a CSV file named sales.csv.
📋 What You'll Learn
Create a dictionary called sales with bread types as keys and number of items sold as values.
Create a list called headers with two strings: 'Bread' and 'Quantity'.
Use the csv module to write the dictionary data into a CSV file named sales.csv.
The CSV file should have a header row with the column names from headers.
💡 Why This Matters
🌍 Real World
Exporting data to CSV files is common in business to share reports, sales data, or any tabular information with others who may use spreadsheet software.
💼 Career
Data analysts and scientists often export processed data to CSV files for reporting, sharing with teams, or further analysis in other tools.
Progress0 / 4 steps
1
Create the sales data dictionary
Create a dictionary called sales with these exact entries: 'Baguette': 30, 'Sourdough': 20, 'Rye': 15, 'Focaccia': 10.
Data Analysis Python
Hint
Use curly braces {} to create a dictionary with keys and values separated by colons.
2
Create the CSV header list
Create a list called headers with two strings: 'Bread' and 'Quantity'.
Data Analysis Python
Hint
Use square brackets [] to create a list with the two column names as strings.
3
Write the sales data to a CSV file
Import the csv module. Open a file named sales.csv in write mode as file. Create a csv.writer object called writer using file. Write the headers list as the first row. Then, use a for loop with variables bread and quantity to iterate over sales.items() and write each bread and quantity as a row using writer.writerow.
Data Analysis Python
Hint
Use csv.writer to write rows. Remember to write the header first, then loop through the dictionary items to write each row.
4
Print confirmation message
Write a print statement that outputs exactly: "Data exported to sales.csv successfully!".
Data Analysis Python
Hint
Use print() with the exact message inside quotes.
Practice
(1/5)
1. What does the to_csv() method do in pandas?
easy
A. Deletes a CSV file from disk
B. Reads a CSV file into a DataFrame
C. Converts a CSV file to Excel format
D. Exports a DataFrame to a CSV file
Solution
Step 1: Understand the purpose of to_csv()
The to_csv() method is used to save or export a pandas DataFrame to a CSV file format.
Step 2: Differentiate from other methods
Methods like read_csv() are for reading CSV files, not exporting. to_csv() specifically writes data to CSV.
Final Answer:
Exports a DataFrame to a CSV file -> Option D
Quick Check:
to_csv() exports data [OK]
Hint: Remember: 'to' means export/save, 'read' means import/load [OK]
Common Mistakes:
Confusing to_csv() with read_csv()
Thinking it deletes files
Assuming it converts file formats
2. Which of the following is the correct syntax to export a DataFrame named df to a CSV file called data.csv without saving the index?
easy
A. df.to_csv('data.csv', index=False)
B. df.to_csv('data.csv', index=True)
C. df.to_csv('data.csv', save_index=False)
D. df.export_csv('data.csv', index=False)
Solution
Step 1: Identify correct method and parameters
The method to export is to_csv(). To exclude the index, use index=False.
3. Given the code below, what will be the content of the file output.csv?
import pandas as pd
data = {'Name': ['Anna', 'Bob'], 'Age': [28, 34]}
df = pd.DataFrame(data)
df.to_csv('output.csv', index=False)
medium
A. Name,Age
0,Anna,28
1,Bob,34
B. "",Name,Age
0,Anna,28
1,Bob,34
C. Name,Age
Anna,28
Bob,34
D. 43,boB
82,annA
egA,emaN
Solution
Step 1: Understand index=False effect
Setting index=False means row numbers are not saved in the CSV file.
Step 2: Analyze CSV content
The CSV will have header row "Name,Age" and data rows "Anna,28" and "Bob,34" without any index column.
Final Answer:
Name,Age
Anna,28
Bob,34
-> Option C
Quick Check:
Index excluded means no row numbers in CSV [OK]
Hint: Index=False means no row numbers saved in CSV [OK]
Common Mistakes:
Expecting index column to be saved despite index=False
Confusing CSV header with index column
Misreading CSV format with extra commas
4. What is wrong with this code snippet?
import pandas as pd
data = {'A': [1, 2], 'B': [3, 4]}
df = pd.DataFrame(data)
df.to_csv('file.csv', index=No)
medium
A. The filename must be a full path, not just 'file.csv'
B. The parameter index should be a boolean, not 'No'
C. The DataFrame is empty and cannot be saved
D. The method to_csv does not exist
Solution
Step 1: Check parameter types
The index parameter expects a boolean value: True or False.
Step 2: Identify the error
Using index=No is invalid because 'No' is not a boolean and will cause a NameError.
Final Answer:
The parameter index should be a boolean, not 'No' -> Option B
Quick Check:
Use True or False for index [OK]
Hint: Boolean parameters must be True or False, not words [OK]
Common Mistakes:
Using strings like 'No' or 'Yes' instead of booleans
Misspelling method names
Assuming filename must be absolute path
5. You have a DataFrame df with columns ['Name', 'Score']. You want to export only the Name column to a CSV file named names.csv without the index. Which code snippet achieves this?
hard
A. df[['Name']].to_csv('names.csv', index=False)
B. df.to_csv('names.csv', columns='Name', index=False)
C. df.to_csv('names.csv', index=False, columns=['name'])
D. df.to_csv('names.csv', index=False, usecols=['Name'])
Solution
Step 1: Select only the 'Name' column
Using df[['Name']] creates a DataFrame with just the 'Name' column.
Step 2: Export without index
Calling to_csv() with index=False saves the file without row numbers.
Step 3: Check other options
Options A, C, and D use incorrect parameters for selecting columns in to_csv().
Final Answer:
df[['Name']].to_csv('names.csv', index=False) -> Option A
Quick Check:
Select columns first, then export [OK]
Hint: Select columns first with df[['Name']], then export [OK]
Common Mistakes:
Using columns='Name' (string instead of list)
Using usecols which is for reading, not writing
Exporting whole DataFrame without selecting columns
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.