🐹 Go

Go 1.21 में शब्दकोश और हैश तालिका: एक विस्तृत मार्गदर्शिका

Dictionaries and Hash Tables in Go

What is a dictionary and why is it needed?

Imagine you have a magic box where you can put anything, but to retrieve an item, you need to say its name (key). For example, you put "Moscow" → "Hello", "London" → "Hello" into the box. Now, if you say "Moscow", the box will immediately give you "Hello".

In programming, such a box is called a dictionary (or hash table). In Go, it is called a map.

A dictionary stores pairs of key → value. Keys must be unique (there cannot be two identical keys), but values can repeat.

Basic Syntax

In Go, a dictionary is created like this:

// Creating an empty dictionary
var myMap map[string]string
myMap = make(map[string]string)

// Or immediately with data
greetings := map[string]string{
    "Russia": "Hello",
    "England": "Hello",
    "France": "Bonjour",
}

Here, string (first) is the key type, string (second) is the value type.

How to work with a dictionary

Let's break down the basic operations using a greetings example:

package main

import "fmt"

func main() {
    // Creating a dictionary
    greetings := map[string]string{
        "Russia": "Hello",
        "England": "Hello",
        "France": "Bonjour",
    }

    // Adding a new entry
    greetings["Germany"] = "Hallo"

    // Getting a value by key
    fmt.Println("In Russia they say:", greetings["Russia"])

    // Checking if a key exists in the dictionary
    value, exists := greetings["Italy"]
    if exists {
        fmt.Println("In Italy they say:", value)
    } else {
        fmt.Println("Italy is not in the dictionary")
    }

    // Deleting an entry
    delete(greetings, "France")

    // Printing all entries
    fmt.Println("All greetings:")
    for country, greeting := range greetings {
        fmt.Println(country, "→", greeting)
    }
}

Analysis of Typical Tasks

Task 1: Phonebook

Need to find a phone number by a person's name.

package main

import "fmt"

func main() {
    // Dictionary: name → phone number
    phonebook := map[string]string{
        "Anna":    "+7-999-123-45-67",
        "Ivan":    "+7-999-765-43-21",
        "Maria":   "+7-999-555-55-55",
    }

    var name string
    fmt.Print("Enter name: ")
    fmt.Scan(&name)

    // Searching for the number
    number, found := phonebook[name]
    if found {
        fmt.Println("Phone number:", number)
    } else {
        fmt.Println("No contact with that name")
    }
}

Task 2: Weekly Planner (To-Do List)

Store a list of tasks for each day of the week.

package main

import "fmt"

func main() {
    // Dictionary: day of week → list of tasks
    tasks := map[string][]string{
        "Monday":    {"Buy groceries", "Go to the bank"},
        "Tuesday":     {"Call a friend"},
        "Wednesday":       {"Clean the room", "Read a book"},
    }

    // Adding a new task for Tuesday
    tasks["Tuesday"] = append(tasks["Tuesday"], "Do homework")

    // Printing all tasks for the week
    fmt.Println("Weekly plan:")
    for day, dayTasks := range tasks {
        fmt.Println(day + ":")
        for _, task := range dayTasks {
            fmt.Println("  -", task)
        }
    }
}

Task 3: Deleting a Contact (Digital Notebook)

Delete a contact that is no longer needed.

package main

import "fmt"

func main() {
    contacts := map[string]string{
        "Oleg":   "+7-111-222-33-44",
        "Nastya":  "+7-555-666-77-88",
        "Dima":   "+7-999-000-11-22",
    }

    fmt.Println("Current contacts:")
    for name, phone := range contacts {
        fmt.Println(name, ":", phone)
    }

    var nameToDelete string
    fmt.Print("Enter name to delete: ")
    fmt.Scan(&nameToDelete)

    // Deleting the contact
    delete(contacts, nameToDelete)
    fmt.Println("After deletion:")
    for name, phone := range contacts {
        fmt.Println(name, ":", phone)
    }
}

Task 4: Dictionary Keys (Product List)

Print all product names from the dictionary.

package main

import "fmt"

func main() {
    // Dictionary: product name → price
    products := map[string]float64{
        "Bread":   45.50,
        "Milk": 89.90,
        "Apples": 120.00,
        "Cheese":    350.00,
    }

    fmt.Println("Available products:")
    for product := range products {
        // Using only keys
        fmt.Println("-", product)
    }

    // Can get all keys separately
    var productList []string
    for product := range products {
        productList = append(productList, product)
    }
    fmt.Println("\nProduct list:", productList)
}

Common Beginner Mistakes

  • Accessing a non-existent key — Go will not throw an error, but will return a zero value (0 for numbers, "" for strings). Always check using value, exists := map[key].
  • Attempting to write to a nil map — if you don't call make(), the map will be nil and writing to it will cause a panic. Always create using make() or immediately with data.
  • Element order — in Go, a map does not guarantee the order of keys during iteration. If order is needed, save the keys in a separate slice and sort it.

Final Example: Traveler's Dictionary

Let's combine everything we've learned:

package main

import "fmt"

func main() {
    // Creating a greetings dictionary
    dictionary := map[string]string{
        "Russia":  "Hello",
        "England":  "Hello",
        "Spain": "Hola",
        "Japan":  "Konnichiwa",
    }

    fmt.Println("My traveler's dictionary:")
    for country, greeting := range dictionary {
        fmt.Printf