Project Overview 💡
In this project, you’ll build a bilingual vocabulary tool that allows users to enter word pairs in two languages and save the vocabulary to a CSV file. This is a practical project for learning how to use dictionaries, loops, and CSV file handling in Python.
Challenge Yourself! 🚀
Before checking the solution, try building the vocabulary tool on your own to check how far your skills can take you.
Task:
Write a Python script that:
Continuously prompts the user to enter a word and its translation
Stores the word pairs in a dictionary
Saves the dictionary to a CSV file
Displays the vocabulary list at the end
Expected Output: The user enters a word in English (e.g., “king”) and its translation to another language (e.g., “mbret”). The user can enter as many word pairs as they want.
The program prints the complete bilingual dictionary to the terminal and saves the files in a CSV file which looks like this:
Try to code the program and then scroll down when you're ready for the step-by-step guide.
Spoiler Alert!
Step-by-Step Guide
Step 1️⃣: Import Required Library
We’ll use the built-in csv
module to save the vocabulary to a CSV file.
import csv
Step 2️⃣: Create an Empty Dictionary
Set up a dictionary to store the vocabulary pairs.
bilingual_vocabulary = {}
Step 3️⃣: Collect Words Using a Loop
Use a while
loop to keep asking the user for input until they type 'done'.
while True:
word_lang1 = input("Enter a word in Language 1 (or type 'done' to finish): ").strip()
if word_lang1.lower() == 'done':
break
translation_lang2 = input(f"Enter the translation of '{word_lang1}' in Language 2: ").strip()
bilingual_vocabulary[word_lang1] = translation_lang2
print(f"'{word_lang1}' (Language 1) has been added with the translation: '{translation_lang2}' (Language 2)\n")
Step 4️⃣: Save the Dictionary to a CSV File
Write the dictionary entries to a .csv
file with headers.
with open('bilingual_vocabulary.csv', mode='w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Language 1', 'Language 2'])
for word_lang1, translation_lang2 in bilingual_vocabulary.items():
writer.writerow([word_lang1, translation_lang2])
Step 5️⃣: Print the Final Vocabulary
Display all collected word pairs on the screen.
print("\nYour Bilingual Vocabulary List:")
for word_lang1, translation_lang2 in bilingual_vocabulary.items():
print(f"{word_lang1} (Language 1): {translation_lang2} (Language 2)")
print("\nThe vocabulary has been saved to 'bilingual_vocabulary.csv'.")
Complete Code 🧨
import csv
# Initialize an empty dictionary to store the bilingual vocabulary
bilingual_vocabulary = {}
# Start a while loop to continually prompt the user for input
while True:
# Ask the user to enter a word in the first language (Language 1)
word_lang1 = input("Enter a word in Language 1 (or type 'done' to finish): ").strip()
# Check if the user wants to stop adding words
if word_lang1.lower() == 'done':
break
# Ask the user to enter the translation in the second language (Language 2)
translation_lang2 = input(f"Enter the translation of '{word_lang1}' in Language 2: ").strip()
# Add the word and its translation to the dictionary
bilingual_vocabulary[word_lang1] = translation_lang2
# Confirm that the word was added
print(f"'{word_lang1}' (Language 1) has been added with the translation: '{translation_lang2}' (Language 2)\n")
# Saving the dictionary to a CSV file
with open('bilingual_vocabulary.csv', mode='w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Language 1', 'Language 2']) # Write the header
for word_lang1, translation_lang2 in bilingual_vocabulary.items():
writer.writerow([word_lang1, translation_lang2]) # Write each word and its translation
# Print out the final dictionary of bilingual vocabulary words
print("\nYour Bilingual Vocabulary List:")
for word_lang1, translation_lang2 in bilingual_vocabulary.items():
print(f"{word_lang1} (Language 1): {translation_lang2} (Language 2)")
print("\nThe vocabulary has been saved to 'bilingual_vocabulary.csv'.")
Alternative Solution
Here’s another version that uses the third-party pandas library instead of the standard csv library. Make sure to install pandas first with “pip install pandas” in the terminal.
import pandas as pd
# Initialize empty lists to store words and translations
lang1_words = []
lang2_words = []
# Collect user input
while True:
word_lang1 = input("Enter a word in Language 1 (or type 'done' to finish): ").strip()
if word_lang1.lower() == 'done':
break
translation_lang2 = input(f"Enter the translation of '{word_lang1}' in Language 2: ").strip()
lang1_words.append(word_lang1)
lang2_words.append(translation_lang2)
print(f"'{word_lang1}' (Language 1) has been added with the translation: '{translation_lang2}' (Language 2)\n")
# Create a DataFrame
df = pd.DataFrame({'Language 1': lang1_words, 'Language 2': lang2_words})
# Save to CSV
df.to_csv('bilingual_vocabulary.csv', index=False)
# Display the vocabulary
print("\nYour Bilingual Vocabulary List:")
print(df.to_string(index=False))
print("\nThe vocabulary has been saved to 'bilingual_vocabulary.csv'.")
Comparison
The original version uses a dictionary and provides user feedback after each entry. It uses the csv module to manually write the vocabulary to a file and loops through the dictionary to display the final vocabulary list.
The alternative version uses two lists and a pandas DataFrame, offering better integration with data analysis tools and a more concise saving and display process. It simplifies file output with to_csv() and improves readability when showing the final vocabulary list.
Want More? 🔥
Enjoyed this project? Unlock real-world projects with full guides & solutions by subscribing to the paid plan. 🎉