Your task is to create a simple dictionary that stores key-value pairs. A dictionary is one of the most powerful data structures in programming, allowing you to store and access data efficiently by using keys instead of indexes.
For example:
"name: Alice"
, "age: 25"
, "city: New York"
.{"name": "Alice", "age": 25, "city": "New York"}
.Dictionaries (or hash maps) are commonly used in programming to:
By learning how to work with dictionaries, you’ll take a big step toward solving more complex data-processing problems.
# Initialize an empty dictionary
dictionary = {}
print("Enter key-value pairs (format: key:value). Type 'done' to finish.")
while True:
# Get input from the user
entry = input("Enter key-value pair: ")
# Exit loop if the user types 'done'
if entry.lower() == "done":
break
# Split input into key and value
if ":" in entry:
key, value = entry.split(":", 1)
dictionary[key.strip()] = value.strip()
else:
print("Invalid format. Use 'key:value'.")
# Output the dictionary
print("\nYour dictionary:")
print(dictionary)
# Allow the user to retrieve values
while True:
key = input("\nEnter a key to retrieve its value (or type 'exit' to quit): ")
if key.lower() == "exit":
break
elif key in dictionary:
print(f"The value for '{key}' is: {dictionary[key]}")
else:
print(f"Key '{key}' not found in the dictionary.")
import java.util.HashMap;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
HashMap<String, String> dictionary = new HashMap<>();
Scanner scanner = new Scanner(System.in);
System.out.println("Enter key-value pairs (format: key:value). Type 'done' to finish.");
while (true) {
// Get input from the user
System.out.print("Enter key-value pair: ");
String entry = scanner.nextLine();
// Exit loop if the user types 'done'
if (entry.equalsIgnoreCase("done")) {
break;
}
// Split input into key and value
if (entry.contains(":")) {
String[] parts = entry.split(":", 2);
dictionary.put(parts[0].trim(), parts[1].trim());
} else {
System.out.println("Invalid format. Use 'key:value'.");
}
}
// Output the dictionary
System.out.println("\nYour dictionary:");
System.out.println(dictionary);
}
}
System.out.println("\nRetrieve values from the dictionary.");
while (true) {
System.out.print("Enter a key to retrieve its value (or type 'exit' to quit): ");
String key = scanner.nextLine();
if (key.equalsIgnoreCase("exit")) {
break;
} else if (dictionary.containsKey(key)) {
System.out.println("The value for '" + key + "' is: " + dictionary.get(key));
} else {
System.out.println("Key '" + key + "' not found.");
}
}
// Initialize an empty object
let dictionary = {};
console.log("Enter key-value pairs (format: key:value). Type 'done' to finish.");
while (true) {
// Get input from the user
let entry = prompt("Enter key-value pair:");
// Exit loop if the user types 'done'
if (entry.toLowerCase() === "done") {
break;
}
// Split input into key and value
if (entry.includes(":")) {
let [key, value] = entry.split(":").map(str => str.trim());
dictionary[key] = value;
} else {
console.log("Invalid format. Use 'key:value'.");
}
}
// Output the dictionary
console.log("\nYour dictionary:", dictionary);
while (true) {
let key = prompt("Enter a key to retrieve its value (or type 'exit' to quit):");
if (key.toLowerCase() === "exit") {
break;
} else if (key in dictionary) {
console.log(`The value for '${key}' is: ${dictionary[key]}`);
} else {
console.log(`Key '${key}' not found in the dictionary.`);
}
}
"Name"
vs. "name"
).In Day 21: Average Calculator, you write a program that calculates the average of a list of numbers provided by the user.