Table of Contents

    Maps / Dictionaries

    Programming Mastery

    Maps / Dictionaries

    Learn how maps and dictionaries store data using key-value pairs and help programmers retrieve information quickly using meaningful keys.

    What are Maps / Dictionaries?

    A map or dictionary is a data structure that stores data in the form of key-value pairs.

    In a map or dictionary, each key is connected to a specific value. Instead of accessing data by position like a list or array, we access data by using a meaningful key.

    A map or dictionary stores values using unique keys, so each value can be quickly found by its key.

    Example:

    student = {
        "name": "Aman",
        "age": 20,
        "course": "Programming"
    }

    Here, "name", "age", and "course" are keys. Their related values are "Aman", 20, and "Programming".

    Easy Real-Life Example

    Dictionary as a Phone Contact List

    Imagine your phone contact list. You search a person's name and get their phone number. The name works like a key, and the phone number works like a value.

    contacts = {
        "Aman": "9876543210",
        "Riya": "9123456780",
        "Sohan": "9988776655"
    }

    To find Riya's number, we do not need to search by position. We can directly use the key "Riya".

    contacts["Riya"] → "9123456780"

    Why are Maps / Dictionaries Used?

    Maps and dictionaries are used when data should be accessed by a meaningful name, ID, code, or label instead of a numeric index.

    A list stores data by position:

    student = ["Aman", 20, "Programming"]
    
    student[0] → "Aman"
    student[1] → 20

    But a dictionary stores data by keys:

    student = {
        "name": "Aman",
        "age": 20,
        "course": "Programming"
    }
    
    student["name"] → "Aman"
    student["age"] → 20
    Key Idea: Use a map or dictionary when you want to look up values by meaningful keys.

    Maps / Dictionaries are Used For

    • Storing student profiles.
    • Storing product details.
    • Storing contact names and phone numbers.
    • Counting frequency of words or numbers.
    • Mapping usernames to passwords or roles.
    • Storing configuration settings.
    • Representing JSON-like data.
    • Creating lookup tables.
    • Storing cache values.
    • Managing IDs and related records.

    Important Terms Related to Maps / Dictionaries

    Term Meaning Example
    Map / Dictionary A data structure that stores key-value pairs. {"name": "Aman"}
    Key A unique identifier used to access a value. "name"
    Value The data associated with a key. "Aman"
    Entry / Pair One key and its related value. "age": 20
    Lookup Finding a value using its key. student["name"]
    Mutable Can be changed after creation. Add, update, remove entries.
    Hash Table A common internal technique used for fast key-based access. Used by many dictionary/map implementations.

    General Syntax of Maps / Dictionaries

    The exact syntax differs across programming languages, but the general structure is:

    dictionaryName = {
        key1: value1,
        key2: value2,
        key3: value3
    }

    Example:

    student = {
        "id": 101,
        "name": "Riya",
        "marks": 92
    }

    Here, each key is followed by its value.

    Language-Neutral Note: Some languages call this structure a dictionary, some call it a map, hashmap, associative array, object, or key-value store.

    Keys Must Usually Be Unique

    In maps and dictionaries, keys are usually unique. This means the same key cannot normally store two different values at the same time.

    student = {
        "name": "Aman",
        "name": "Riya"
    }

    If duplicate keys are used, many languages keep the latest value or overwrite the previous value.

    Final value of "name" may become "Riya"
    Important: Keys should be unique because each key identifies one value.

    Values Can Be Different Types

    Values in a dictionary can often be numbers, text, lists, sets, other dictionaries, objects, or any supported data type.

    student = {
        "name": "Aman",
        "age": 20,
        "isActive": true,
        "skills": ["Programming", "Database", "Communication"]
    }

    This makes dictionaries very useful for storing structured real-world data.

    Accessing Values Using Keys

    We access values in a dictionary using their keys.

    /*
    This program accesses values from a dictionary.
    */
    
    ENTRY POINT
        DECLARE student AS DICTIONARY = {
            "name": "Aman",
            "age": 20,
            "course": "Programming"
        }
    
        DISPLAY student["name"]
        DISPLAY student["age"]
        DISPLAY student["course"]
    END ENTRY POINT

    Expected Output

    Aman
    20
    Programming

    Adding a New Key-Value Pair

    We can add a new key-value pair to a dictionary by assigning a value to a new key.

    /*
    This program adds a new key-value pair.
    */
    
    ENTRY POINT
        DECLARE student AS DICTIONARY = {
            "name": "Riya",
            "age": 21
        }
    
        SET student["course"] = "Database"
    
        DISPLAY student
    END ENTRY POINT

    Expected Output

    {
        "name": "Riya",
        "age": 21,
        "course": "Database"
    }

    Updating an Existing Value

    If a key already exists, assigning a new value to that key updates the old value.

    /*
    This program updates an existing value.
    */
    
    ENTRY POINT
        DECLARE product AS DICTIONARY = {
            "name": "Keyboard",
            "price": 500
        }
    
        SET product["price"] = 450
    
        DISPLAY product["price"]
    END ENTRY POINT

    Expected Output

    450

    Removing a Key-Value Pair

    We can remove a key-value pair when it is no longer needed.

    /*
    This program removes a key-value pair.
    */
    
    ENTRY POINT
        DECLARE user AS DICTIONARY = {
            "name": "Sohan",
            "email": "sohan@example.com",
            "temporaryCode": "ABC123"
        }
    
        REMOVE KEY "temporaryCode" FROM user
    
        DISPLAY user
    END ENTRY POINT

    Expected Output

    {
        "name": "Sohan",
        "email": "sohan@example.com"
    }

    Checking Whether a Key Exists

    Before accessing a value, it is often a good idea to check whether the key exists.

    /*
    This program checks whether a key exists.
    */
    
    ENTRY POINT
        DECLARE settings AS DICTIONARY = {
            "theme": "dark",
            "language": "English"
        }
    
        IF "theme" EXISTS IN settings THEN
            DISPLAY settings["theme"]
        ELSE
            DISPLAY "Theme setting not found"
        END IF
    END ENTRY POINT

    Expected Output

    dark

    Traversing a Map / Dictionary

    Traversing a dictionary means visiting its keys, values, or key-value pairs one by one.

    Traversing Keys

    /*
    This program displays all keys.
    */
    
    ENTRY POINT
        DECLARE student AS DICTIONARY = {
            "name": "Aman",
            "age": 20,
            "course": "Programming"
        }
    
        FOR EACH key IN student
            DISPLAY key
        END FOR
    END ENTRY POINT

    Expected Output

    name
    age
    course

    Traversing Values

    /*
    This program displays all values.
    */
    
    ENTRY POINT
        DECLARE student AS DICTIONARY = {
            "name": "Aman",
            "age": 20,
            "course": "Programming"
        }
    
        FOR EACH key IN student
            DISPLAY student[key]
        END FOR
    END ENTRY POINT

    Expected Output

    Aman
    20
    Programming

    Common Map / Dictionary Operations

    Operation Meaning Example Idea
    Create Create a new dictionary. {"name": "Aman"}
    Access / Lookup Get value using key. student["name"]
    Add Add a new key-value pair. student["city"] = "Kolkata"
    Update Change value of an existing key. student["age"] = 21
    Remove Delete a key-value pair. Remove "temporaryCode"
    Check Key Check whether a key exists. "email" IN user
    Keys Get all keys. name, age, course
    Values Get all values. Aman, 20, Programming
    Items / Entries Get all key-value pairs. ("name", "Aman")

    Example: Student Record Using Dictionary

    /*
    This program stores a student record using a dictionary.
    */
    
    ENTRY POINT
        DECLARE student AS DICTIONARY = {
            "id": 101,
            "name": "Meera",
            "marks": 88,
            "grade": "A"
        }
    
        DISPLAY "Student ID: " + student["id"]
        DISPLAY "Name: " + student["name"]
        DISPLAY "Marks: " + student["marks"]
        DISPLAY "Grade: " + student["grade"]
    END ENTRY POINT

    Expected Output

    Student ID: 101
    Name: Meera
    Marks: 88
    Grade: A

    Example: Count Frequency Using Dictionary

    Dictionaries are very useful for counting how many times each value appears.

    /*
    This program counts frequency of numbers.
    */
    
    ENTRY POINT
        DECLARE numbers AS LIST = [10, 20, 10, 30, 20, 10]
        DECLARE frequency AS DICTIONARY = {}
    
        FOR EACH number IN numbers
            IF number EXISTS IN frequency THEN
                SET frequency[number] = frequency[number] + 1
            ELSE
                SET frequency[number] = 1
            END IF
        END FOR
    
        DISPLAY frequency
    END ENTRY POINT

    Expected Output

    {
        10: 3,
        20: 2,
        30: 1
    }

    Example: Product Price Lookup

    /*
    This program uses a dictionary as a price lookup table.
    */
    
    ENTRY POINT
        DECLARE prices AS DICTIONARY = {
            "Pen": 10,
            "Notebook": 50,
            "Bag": 700
        }
    
        DECLARE productName AS TEXT = "Notebook"
    
        IF productName EXISTS IN prices THEN
            DISPLAY productName + " price is " + prices[productName]
        ELSE
            DISPLAY "Product not found"
        END IF
    END ENTRY POINT

    Expected Output

    Notebook price is 50

    Nested Dictionaries

    A dictionary can contain another dictionary as a value. This is called a nested dictionary.

    students = {
        "101": {
            "name": "Aman",
            "marks": 85
        },
        "102": {
            "name": "Riya",
            "marks": 92
        }
    }

    Nested dictionaries are useful for storing structured data such as student records, product details, user profiles, and API responses.

    students["102"]["name"] → "Riya"

    Map / Dictionary vs List

    Feature List Map / Dictionary
    Storage Style Stores values in sequence. Stores key-value pairs.
    Access Method Access by index. Access by key.
    Example Access items[0] student["name"]
    Best For Ordered collections. Labeled or named data.
    Meaning of Position Position matters. Key meaning matters.

    Map / Dictionary vs Set

    Feature Set Map / Dictionary
    Stores Unique values only. Key-value pairs.
    Duplicates Duplicate values not allowed. Duplicate keys not allowed.
    Lookup Check if value exists. Get value using key.
    Example {"Admin", "Editor"} {"role": "Admin"}

    Why Maps / Dictionaries are Fast for Lookup

    Many map and dictionary implementations use hashing or similar techniques internally.

    This means they are usually designed to quickly find a value using its key.

    contacts["Riya"] → quickly returns Riya's phone number
    Beginner Note: You do not need to understand hashing deeply at first. Just remember that maps and dictionaries are very useful for key-based lookup.

    Advantages of Maps / Dictionaries

    Benefits

    • They store data in meaningful key-value pairs.
    • They allow fast lookup using keys.
    • They are useful for structured records.
    • They make code more readable than using numeric indexes.
    • They can grow and shrink dynamically in many languages.
    • They are useful for counting frequencies.
    • They work well for configuration, caching, and lookup tables.
    • They are commonly used in JSON-like data structures.

    Limitations of Maps / Dictionaries

    Limitations

    • Keys must usually be unique.
    • Duplicate keys may overwrite old values.
    • Some languages require keys to be immutable or hashable.
    • Accessing a missing key may cause an error in some languages.
    • They are not ideal when order by position is the main requirement.
    • Nested dictionaries can become difficult to read if not organized carefully.

    Common Beginner Mistakes

    Mistakes

    • Trying to access dictionary values using numeric indexes like a list.
    • Using duplicate keys and expecting both values to remain.
    • Forgetting to check whether a key exists before accessing it.
    • Confusing keys and values.
    • Using unclear key names.
    • Storing unrelated data in one dictionary without structure.
    • Creating deeply nested dictionaries that are hard to read.
    • Assuming every language keeps dictionary order in the same way.

    Better Habits

    • Use meaningful keys such as "name", "email", and "price".
    • Check whether a key exists before accessing optional data.
    • Use dictionaries for labeled data, not simple ordered lists.
    • Keep nested dictionaries readable with proper indentation.
    • Use consistent key naming style.
    • Remember that keys should be unique.
    • Use dictionaries for lookup tables and frequency counting.
    • Test with missing keys and empty dictionaries.

    Best Practices for Maps / Dictionaries

    Recommended Practices

    • Use maps or dictionaries when data has labels or identifiers.
    • Use keys that clearly describe the value.
    • Use consistent key names across similar dictionaries.
    • Check for missing keys when data is optional.
    • Use dictionaries for fast lookup by ID, name, code, or category.
    • Use dictionaries for frequency counting problems.
    • Use nested dictionaries only when the structure is clear.
    • Avoid using mutable values as keys in languages that do not allow them.
    • Use comments for complex dictionary structures.
    • Practice maps with real-world examples such as contacts, products, student records, and settings.

    Prerequisites Before Learning Maps / Dictionaries

    Students should already understand:

    Required Knowledge

    • Variables and constants.
    • Data types.
    • Input and output.
    • Conditions.
    • Loops and iteration.
    • Lists and arrays.
    • Sets and uniqueness.
    • Basic searching and lookup idea.

    Trace Table Example: Frequency Count

    Let us trace how a dictionary counts repeated values.

    numbers = [2, 3, 2, 4, 3]
    frequency = {}
    
    FOR EACH number IN numbers
        IF number EXISTS IN frequency THEN
            frequency[number] = frequency[number] + 1
        ELSE
            frequency[number] = 1
        END IF
    END FOR
    Step Current Number Action Dictionary Status
    1 2 Add key 2 with count 1 {2: 1}
    2 3 Add key 3 with count 1 {2: 1, 3: 1}
    3 2 Increase count of key 2 {2: 2, 3: 1}
    4 4 Add key 4 with count 1 {2: 2, 3: 1, 4: 1}
    5 3 Increase count of key 3 {2: 2, 3: 2, 4: 1}

    Practice Activity: Work with a Dictionary

    Study the following dictionary:

    book = {
        "title": "Programming Basics",
        "author": "Rumman",
        "price": 499
    }

    Questions

    1. What is the value of book["title"]?
    2. What is the value of book["price"]?
    3. Add a new key "pages" with value 250.
    4. Update "price" to 399.
    5. Remove the key "author".

    Sample Answers

    1. Programming Basics
    2. 499
    3. book["pages"] = 250
    4. book["price"] = 399
    5. REMOVE KEY "author" FROM book

    Mini Quiz

    1

    What is a map or dictionary?

    A map or dictionary is a data structure that stores data in key-value pairs.

    2

    What is a key?

    A key is a unique identifier used to access a related value.

    3

    What is a value?

    A value is the data stored against a key.

    4

    Can keys be duplicated?

    Usually no. Keys should be unique. Duplicate keys may overwrite previous values.

    5

    When should we use a dictionary?

    We should use a dictionary when we need to access values using meaningful keys such as names, IDs, or labels.

    Interview Questions on Maps / Dictionaries

    1

    Define map or dictionary in programming.

    A map or dictionary is a data structure that stores values using unique keys.

    2

    How is a dictionary different from a list?

    A list stores values by position, while a dictionary stores values by keys.

    3

    What are common dictionary operations?

    Common operations include create, access, add, update, remove, check key, traverse keys, traverse values, and traverse key-value pairs.

    4

    Why are dictionaries useful for frequency counting?

    Dictionaries can store each unique item as a key and its count as the value.

    5

    What happens when we access a missing key?

    In some languages, accessing a missing key may return a default value; in others, it may cause an error. So it is safer to check whether the key exists first.

    Quick Summary

    Concept Meaning
    Map / Dictionary Stores data as key-value pairs.
    Key Unique identifier used for lookup.
    Value Data associated with a key.
    Lookup Accessing value using key.
    Add Insert a new key-value pair.
    Update Change value of an existing key.
    Remove Delete a key-value pair.
    Best Use Profiles, records, settings, lookup tables, and frequency counting.

    Final Takeaway

    Maps and dictionaries are powerful data structures for storing data as key-value pairs. They make programs more readable because values can be accessed using meaningful keys instead of numeric positions. In the Programming Mastery Course, students should understand maps and dictionaries as essential tools for records, lookups, configuration data, frequency counting, contact lists, product catalogs, user profiles, and many real-world programming problems.