Day 20: Simple Dictionary

Objective

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:

  • Input: Add key-value pairs like "name: Alice", "age: 25", "city: New York".
  • Output: A dictionary containing the entered key-value pairs: {"name": "Alice", "age": 25, "city": "New York"}.

Why This Challenge Is Important

Dictionaries (or hash maps) are commonly used in programming to:

  1. Organize and store data in a structured format.
  2. Perform fast lookups based on keys.
  3. Represent real-world objects with properties, like a person or a product.

By learning how to work with dictionaries, you’ll take a big step toward solving more complex data-processing problems.


Steps to Solve

1. Understand the Problem

  • The user will input multiple key-value pairs.
  • These pairs will be stored in a dictionary.
  • Allow the user to retrieve or display the dictionary after entering the data.

2. Basic Plan

  1. Prompt the user to enter key-value pairs.
  2. Split the input into a key and value.
  3. Add the key-value pair to the dictionary.
  4. Allow the user to view the dictionary or retrieve a value by key.

3. Advanced Features to Include

  • Prevent duplicate keys by replacing old values with new ones.
  • Allow the user to exit the input loop.

Code Examples

Python Example

Creating a Simple Dictionary:

# 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)

Retrieving Values by Key:

# 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.")

Java Example

Creating a Simple 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);
    }
}

Retrieving Values by Key:

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.");
    }
}

JavaScript Example

Creating a Simple Dictionary:

// 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);

Retrieving Values by Key:

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.`);
    }
}

Edge Cases to Consider

  1. Duplicate Keys: Ensure the latest value overwrites any previous value for the same key.
  2. Empty Input: Handle cases where the user provides no input.
  3. Invalid Format: Handle incorrectly formatted inputs gracefully.
  4. Case Sensitivity: Decide whether keys should be case-sensitive (e.g., "Name" vs. "name").

Extensions to Explore

  1. Delete a Key-Value Pair: Allow the user to remove entries from the dictionary.
  2. Update Values: Let the user modify values for existing keys.
  3. Persist Data: Save the dictionary to a file for later use.

What You’ve Learned

  • How to create and manage a dictionary (or hash map).
  • How to add, retrieve, and display key-value pairs.
  • Practical use cases of dictionaries for organizing data.

Next Steps

In Day 21: Average Calculator, you write a program that calculates the average of a list of numbers provided by the user.